OOP IN JAVA PROJECT
OOP IN JAVA PROJECT
public CalculatorFrame() {
// Set up the frame
setTitle("Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Create buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 10, 10));
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.BOLD, 20));
button.addActionListener(this);
buttonPanel.add(button);
}
add(buttonPanel, BorderLayout.CENTER);
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
try {
if (Character.isDigit(command.charAt(0))) {
if (isOperatorPressed) {
inputField.setText(""); // Clear for the second
operand
isOperatorPressed = false;
}
inputField.setText(inputField.getText() + command);
} else if (command.equals("C")) {
// Clear the input field and reset variables
inputField.setText("");
num1 = num2 = result = 0;
operator = '\0';
isOperatorPressed = false;
} else if (command.equals("=")) {
// Perform the calculation
if (operator != '\0' && !
inputField.getText().isEmpty()) {
num2 = Double.parseDouble(inputField.getText());
calculateResult();
inputField.setText(String.valueOf(result));
operator = '\0'; // Reset operator
}
} else {
// Save the operator and the first number
if (!inputField.getText().isEmpty()) {
num1 = Double.parseDouble(inputField.getText());
operator = command.charAt(0);
isOperatorPressed = true;
}
}
} catch (NumberFormatException ex) {
inputField.setText("Error");
}
}