Advanced Java Program: Simple Calculator
Question: Write a Java program to design a simple calculator using GridLayout.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
private StringBuilder input;
public Calculator() {
input = new StringBuilder();
// Set up the frame
setTitle("Advanced Calculator");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create text field for input
textField = new JTextField();
textField.setEditable(false);
textField.setFont(new Font("Arial", Font.PLAIN, 30));
textField.setHorizontalAlignment(JTextField.RIGHT);
// Create panel with GridLayout for the buttons
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4, 10, 10)); // 5 rows and 4 columns
// Button labels
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"C", "(", ")", "%"
};
// Add buttons to panel
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.PLAIN, 20));
button.addActionListener(this);
panel.add(button);
// Add components to frame
add(textField, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
try {
// Evaluate the expression using eval method
String result = String.valueOf(eval(input.toString()));
textField.setText(result);
input.setLength(0); // Clear input after calculation
input.append(result); // Store result for further operations
} catch (Exception ex) {
textField.setText("Error");
} else if (command.equals("C")) {
// Clear the input
input.setLength(0);
textField.setText("");
} else {
// Append the clicked button's text to the input
input.append(command);
textField.setText(input.toString());
}
}
// Method to evaluate the mathematical expression
private double eval(String expression) {
// Simple evaluation using the Java Script engine (for learning purposes)
try {
javax.script.ScriptEngine engine = new
javax.script.ScriptEngineManager().getEngineByName("JavaScript");
return ((Number) engine.eval(expression)).doubleValue();
} catch (Exception e) {
throw new RuntimeException("Invalid Expression");
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Calculator().setVisible(true);
});