7:1: make calculator with minimum fuctionality
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame {
private JTextField textField;
private double firstOperand = 0;
private String operator = "";
private boolean isNewInput = true;
public SimpleCalculator() {
// Set up the JFrame
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
setLayout(new BorderLayout());
// Create and configure the text field
textField = new JTextField();
textField.setFont(new Font("Arial", Font.PLAIN, 24));
textField.setHorizontalAlignment(JTextField.RIGHT);
textField.setEditable(false);
add(textField, BorderLayout.NORTH);
// Create and configure the button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 10, 10));
// Define button labels
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};
// Create buttons and add ActionListener
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.PLAIN, 18));
button.addActionListener(new ButtonClickListener());
buttonPanel.add(button);
}
add(buttonPanel, BorderLayout.CENTER);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (isNewInput) {
textField.setText("");
isNewInput = false;
}
if (command.matches("[0-9]")) {
textField.setText(textField.getText() + command);
} else if (command.matches("[+\\-*/]")) {
operator = command;
firstOperand = Double.parseDouble(textField.getText());
isNewInput = true;
} else if (command.equals("=")) {
double secondOperand = Double.parseDouble(textField.getText());
double result = performOperation(firstOperand, secondOperand, operator);
textField.setText(String.valueOf(result));
isNewInput = true;
} else if (command.equals("C")) {
textField.setText("");
firstOperand = 0;
operator = "";
isNewInput = true;
}
}
}
private double performOperation(double num1, double num2, String operator) {
switch (operator) {
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
if (num2 != 0) {
return num1 / num2;
} else {
return Double.NaN; // Division by zero
}
default:
return num2;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}
No comments