জাভা সুইয়িং ব্যবহার করে একটি ক্যালকুলেটর

Posted on by

Categories:         

একদম শুরুতে যখন আমার জাভা প্রোগ্রামিংয়ের হাতে খড়ি বলা যায়, তখন জাভার সুইয়িং ব্যবহার করে একটি ক্যালকুলেটর তৈরি করেছিলাম।

এটি একটি ফোরামে দিয়েছিলাম। সেখানে অনেকেই পছন্দ করেছিল। হঠাৎ করেই পেয়ে গেলাম প্রায় ৮ বছর আগের একটি কোড।

আজকের এই পোস্টে এই কোডটি শেয়ার করছি।

package com.bazlur.calculator;

public class BasicMath {
	/**
	 * This method adds up the arguments
	 *
	 * @param a first value
	 * @param b second value
	 * @return result of addition
	 */
	public double add(double a, double b) {
		return a + b;
	}

	/**
	 * This method subtract second value from first value
	 *
	 * @param a first value
	 * @param b second value
	 * @return result of subtraction
	 */
	public double minus(double a, double b) {
		return a - b;
	}

	/**
	 * This method perform multiplication
	 *
	 * @param a first value
	 * @param b second value
	 * @return result of multiplication
	 */
	public double multiply(double a, double b) {
		return a * b;
	}

	/**
	 * This method performs the Division. It takes two double as arguments and
	 * returns their division as a result. If the second argument is zero,
	 * usually this could throw an Exception. To handle the exception,
	 * we used try/catch block here, if an exception occurs, we return zero.
	 *
	 * @param a first argument
	 * @param b second argument
	 * @return result of division
	 */

	public double divide(double a, double b) {
		try {
			return a / b;
		} catch (ArithmeticException e) {
			System.err.println(e.getMessage());
		}
		return 0.0;
	}

	/**
	 * This method convert a string value to a double
	 *
	 * @param a a string value
	 * @return double value
	 */
	/* this method defined for make string value to double.. its called parsing */
	public double stringToDouble(String a) {

		return Double.parseDouble(a);
	}
}

package com.bazlur.calculator;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.regex.Pattern;

public class CalculatorUI extends JFrame implements ActionListener {

	private final static Font BIGGER_FONT = new Font("monspaced", Font.PLAIN,
					20);
	private final static String buttonOrder = "789/456*123-0.=+";

	private final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");

	private JTextField txtDisplay;

	private String firstValue;
	private final BasicMath math = new BasicMath();
	private JLabel lblOperation;

	private String currentOperation = "";

	/**
	 * Create the frame.
	 */
	public CalculatorUI() {
		buildUserInterface();

		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				confirmExit();
			}
		});
	}

	private void buildUserInterface() {
		setTitle("Simple Calculator");

		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setBounds(100, 100, 350, 300);
		JPanel contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		txtDisplay = new JTextField("", 12);
		txtDisplay.setHorizontalAlignment(JTextField.RIGHT);
		txtDisplay.setFont(BIGGER_FONT);

		contentPane.add(txtDisplay, BorderLayout.NORTH);
		txtDisplay.setColumns(10);

		JPanel keyPanel = new JPanel();
		contentPane.add(keyPanel, BorderLayout.CENTER);
		keyPanel.setLayout(new GridLayout(0, 4, 10, 10));

		JPanel extraKeyPanel = new JPanel();
		contentPane.add(extraKeyPanel, BorderLayout.SOUTH);

		extraKeyPanel.add(new JButton("Clear"));

		JLabel lblCurrentOperation = new JLabel("Current Operation: ");
		extraKeyPanel.add(lblCurrentOperation);

		this.lblOperation = new JLabel("");
		extraKeyPanel.add(lblOperation);
		new JButton("Clear").addActionListener(this);

		for (int i = 0; i < buttonOrder.length(); i++) {
			String keyName = buttonOrder.substring(i, i + 1);
			JButton key = new JButton(keyName);
			keyPanel.add(key);
			key.addActionListener(this);
		}
	}

	// this method will prompt a dialog box to user to be sure about exit.. ?
	protected void confirmExit() {
		if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
						"Are you sure?", "Exit ?", JOptionPane.OK_CANCEL_OPTION)) {
			this.dispose();
		}
	}

	/**
	 * this method perform operation based on keystroke
	 */
	@Override
	public void actionPerformed(ActionEvent e) {

		String command = e.getActionCommand();
		if (isNumeric(command)) {
			handleNumericNumbers(command);
		} else if (command.endsWith(".")) {
			handleDotOperator();
		} else if ("+-*/".contains(command)) {
			handleOps(command);
		} else if (command.endsWith("=")) {
			performCalculation();
		} else if (command.endsWith("Clear")) {
			clear();
		}
	}


	private void performCalculation() {
		lblOperation.setText("=");
		txtDisplay.setText(String.valueOf(doPerformCalculation()));
	}

	/**
	 * Here we fetch the second value, and based on the current operation we perform the calculation.
	 * If the current operator is +, we invoke the add() method from the BasicMath
	 * class. It takes two double variables.
	 * Our values are string,  and that's why we need to convert them into double.
	 * For that, we use stringToDouble() from my BasicMath class. It takes a string parameter and returns double.
	 * Then we pass those double to the add method and get the result and display in the result panel,
	 * which is txtDisplay using the setText method. However, this method takes an only string.
	 * And that's why we have to convert the result into the string again using String.valueOf().
	 * It is a static method of String class. it takes a double parameter and returns
	 * String.
	 */
	private double doPerformCalculation() {
		double first = math.stringToDouble(firstValue);
		double second = math.stringToDouble(txtDisplay.getText());
		double result = 0.0;

		switch (currentOperation) {
			case "+":
				result = math.add(first, second);
				break;
			case "-":
				result = math.minus(first, second);
				break;
			case "/":
				result = math.divide(first, second);
				break;
			case "*":
				result = math.multiply(first, second);
				break;
		}

		return result;
	}

	/**
	 * if clear button press, it clears the txtDisplays
	 */
	public void clear() {
		txtDisplay.setText("");
		lblOperation.setText("");
	}

	private void handleOps(String command) {
		currentOperation = command;
		firstValue = txtDisplay.getText();
		txtDisplay.setText("");
		lblOperation.setText(currentOperation);
	}

	/**
	 * if user used dot once already, we are not allowing to sue it again
	 */
	private void handleDotOperator() {
		String text = txtDisplay.getText();
		if (!text.contains(".")) {
			txtDisplay.setText(text + ".");
		}
	}

	private void handleNumericNumbers(String command) {

		txtDisplay.setText(txtDisplay.getText() + command);
	}

	public boolean isNumeric(String strNum) {
		if (strNum == null) {

			return false;
		}
		
		return pattern.matcher(strNum).matches();
	}
}

 

package com.bazlur.calculator;

import javax.swing.*;
import java.awt.*;

public class Application {
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(() -> {
			try {
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
				CalculatorUI frame = new CalculatorUI();
				frame.setVisible(true);
			} catch (Exception e) {
				System.err.println("Unable to lunch application deu to " + e.getMessage());
			}
		});
	}
}

ওপরের কোডগুলো কপি করে রান করুন। তাহলে পেয়ে যাবেন একটি সিম্পল ক্যালকুলেটর।

Calculator

     

Share on:

Author: A N M Bazlur Rahman

Java Champion | Software Engineer | JUG Leader | Book Author | InfoQ & Foojay.IO Editor | Jakarta EE Ambassadors| Helping Java Developers to improve their coding & collaboration skills so that they can meet great people & collaborate

100daysofcode 100daysofjava access advance-java agile algorithm arraylist article bangla-book becoming-expert biginteger book calculator checked checked-exceptions cloning code-readability code-review coding coding-convention collection-framework compact-strings completablefuture concatenation concurrency concurrentmodificationexception concurrentskiplistmap counting countingcollections critical-section daemon-thread data-race data-structure datetime day002 deliberate-practice deserialization design-pattern developers duration execute-around executors export fibonacci file file-copy fork/join-common-pool functional future-java-developers groupby hash-function hashmap history history-of-java how-java-performs-better how-java-works http-client image import inspiration io itext-pdf java java-10 java-11 java-17 java-8 java-9 java-developers java-performance java-programming java-thread java-thread-programming java11 java16 java8 lambda-expression learning learning-and-development linkedlist list local-type-inference localdatetime map methodology microservices nio non-blockingio null-pointer-exception object-cloning optional packaging parallel pass-by-reference pass-by-value pdf performance prime-number programming project-loom race-condition readable-code record refactoring review scheduler scrum serialization serversocket simple-calculator socket software-development softwarearchitecture softwareengineering sorting source-code stack string string-pool stringbuilder swing thread threads tutorial unchecked vector virtual-thread volatile why-java zoneid