Java GUI Calculator Report 6111 Laiba
Java GUI Calculator Report 6111 Laiba
1. Introduction
This report outlines the creation of a basic calculator using Java's Swing framework. The focus was on
developing a functional graphical user interface (GUI) that supports arithmetic operations. The project
introduced the use of GUI containers, layout managers, and component customization to build a user-
friendly calculator.
2. Java Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
if (text.matches("[0-9]")) {
btn.setBackground(Color.YELLOW);
btn.setForeground(Color.BLACK);
} else {
btn.setBackground(Color.DARK_GRAY);
btn.setForeground(Color.WHITE);
}
btn.addActionListener(e -> {
String btnText = btn.getText();
switch (btnText) {
case "+": case "-": case "*": case "/":
try {
firstNumber[0] = Double.parseDouble(display.getText());
operator[0] = btnText;
input.setLength(0);
display.setText("");
} catch (NumberFormatException ex) {
display.setText("Error");
}
break;
case "=":
try {
double secondNumber = Double.parseDouble(display.getText());
double result = 0;
switch (operator[0]) {
case "+": result = firstNumber[0] + secondNumber; break;
case "-": result = firstNumber[0] - secondNumber; break;
case "*": result = firstNumber[0] * secondNumber; break;
case "/":
if (secondNumber == 0) {
display.setText("Cannot divide by 0");
return;
} else {
result = firstNumber[0] / secondNumber;
}
break;
}
display.setText(String.valueOf(result));
input.setLength(0);
} catch (Exception ex) {
display.setText("Error");
}
break;
default:
input.append(btnText);
display.setText(input.toString());
break;
}
});
panel.add(btn);
}
frame.add(panel, BorderLayout.CENTER);
frame.getContentPane().setBackground(new Color(0, 51, 102));
frame.setVisible(true);
}
}
3. Interface Overview
The calculator features a window containing a display field at the top and a 4x4 grid of buttons below.
Buttons include digits, operations (+, -, *, /), and functional keys such as "." and "=". Color themes are
applied to enhance readability and usability. The deep blue background provides a sleek appearance,
while yellow highlights numeric buttons.
4. Key Takeaways
Output: