Skip to content

Instantly share code, notes, and snippets.

@Malix-off
Last active December 11, 2023 14:15
Show Gist options
  • Save Malix-off/a533111befc0e492f576a1b8d0ee6cf4 to your computer and use it in GitHub Desktop.
Save Malix-off/a533111befc0e492f576a1b8d0ee6cf4 to your computer and use it in GitHub Desktop.
Simplest Java Calculator GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame implements ActionListener {
private JTextField displayField;
private double currentValue = 0;
private String currentOperator = "";
private boolean start = true;
public SimpleCalculator() {
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 10, 10));
displayField = new JTextField("0");
displayField.setEditable(false);
add(displayField, BorderLayout.NORTH);
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
for (String buttonLabel : buttonLabels) {
JButton button = new JButton(buttonLabel);
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
pack();
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
switch (action) {
case "C":
currentValue = 0;
currentOperator = "";
displayField.setText("0");
start = true;
break;
case "+":
case "-":
case "*":
case "/":
if (!currentOperator.isEmpty()) {
performCalculation();
}
currentOperator = action;
currentValue = Double.parseDouble(displayField.getText());
start = true;
break;
case "=":
performCalculation();
currentOperator = "";
start = true;
break;
default:
if (start) {
displayField.setText(action);
start = false;
} else {
displayField.setText(displayField.getText() + action);
}
break;
}
}
private void performCalculation() {
double newValue = Double.parseDouble(displayField.getText());
switch (currentOperator) {
case "+":
currentValue += newValue;
break;
case "-":
currentValue -= newValue;
break;
case "*":
currentValue *= newValue;
break;
case "/":
if (newValue != 0) {
currentValue /= newValue;
} else {
currentValue = Double.NaN; // Division by zero error
}
break;
}
displayField.setText(String.valueOf(currentValue));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment