How to develop a calculator using Java GUI
The following is an example code for a simple Java GUI calculator:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatorGUI extends JFrame implements ActionListener {
private JPanel panel;
private JTextField textField;
private JButton[] buttons;
private String[] buttonLabels = {
\t"7", "8", "9", "/",
\t"4", "5", "6", "*",
\t"1", "2", "3", "-",
\t"0", ".", "=", "+"
};
private String currentInput = "";
private double result = 0;
private String operator = "";
public CalculatorGUI() {
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
textField = new JTextField();
textField.setEditable(false);
buttons = new JButton[buttonLabels.length];
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
add(textField, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Calculator");
setSize(300, 400);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "0": case "1": case "2": case "3": case "4":
case "5": case "6": case "7": case "8": case "9":
currentInput += command;
textField.setText(currentInput);
break;
case ".":
if (!currentInput.contains(".")) {
currentInput += ".";
}
textField.setText(currentInput);
break;
case "/": case "*": case "-": case "+":
operator = command;
result = Double.parseDouble(currentInput);
currentInput = "";
textField.setText("");
break;
case "=":
double secondOperand = Double.parseDouble(currentInput);
switch (operator) {
case "/":
result /= secondOperand;
break;
case "*":
result *= secondOperand;
break;
case "-":
result -= secondOperand;
break;
case "+":
result += secondOperand;
break;
}
currentInput = String.valueOf(result);
textField.setText(currentInput);
break;
default:
break;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CalculatorGUI();
}
});
}
}
You can instantiate the calculator GUI by creating a CalculatorGUI object and use the 'SwingUtilities. invokeLater()' method to launch the application in the event distribution thread.