Creating a **simple calculator using Java in NetBeans** and integrating it with **MySQL** to
store the history of calculations is a great project idea! Here’s a step-by-step guide:
---
### **1. Set Up MySQL Database**
1. **Create the Database**
```sql
CREATE DATABASE CalculatorDB;
```
2. **Use the Database**
```sql
USE CalculatorDB;
```
3. **Create a Table to Store History**
```sql
CREATE TABLE CalculationHistory (
ID INT AUTO_INCREMENT PRIMARY KEY,
Expression VARCHAR(255),
Result VARCHAR(50),
Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
```
1
---
### **2. Create the NetBeans Project**
1. Open NetBeans and create a new project: `File → New Project → Java → Java Application`.
2. Name the project `CalculatorWithHistory`.
---
### **3. Add the MySQL Connector**
- Download the MySQL JDBC driver (`mysql-connector-java.jar`) from [MySQL]
(https://dev.mysql.com/downloads/connector/j/).
- Add the JAR file to your project:
- Right-click on your project → `Properties → Libraries → Add JAR/Folder` → Select the
downloaded JAR.
---
### **4. Design the GUI**
1. Add a `JFrame` to the project: Right-click the `Source Packages` folder → `New → JFrame
Form` → Name it `Calculator`.
2. Design the GUI:
- Add a `JTextField` for displaying input/output.
- Add buttons for digits (`0-9`) and operations (`+`, `-`, `*`, `/`, `=`, `C`).
- Add a `JButton` to view the calculation history.
2
---
### **5. Connect to MySQL Database**
Create a separate class for database operations.
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class DatabaseConnection {
public static Connection connect() {
Connection conn = null;
try {
String url = "jdbc:mysql://localhost:3306/CalculatorDB";
String user = "root"; // Your MySQL username
String password = ""; // Your MySQL password
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
return conn;
3
public static void saveCalculation(String expression, String result) {
try (Connection conn = connect()) {
String query = "INSERT INTO CalculationHistory (Expression, Result) VALUES (?, ?)";
PreparedStatement pst = conn.prepareStatement(query);
pst.setString(1, expression);
pst.setString(2, result);
pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
```
---
### **6. Add Functionality to the Calculator**
Here’s the full code for the calculator.
```java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
4
public class Calculator extends JFrame {
private JTextField display;
private double num1, num2, result;
private String operator;
public Calculator() {
initComponents();
private void initComponents() {
display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setBounds(20, 20, 240, 40);
JButton[] buttons = new JButton[16];
String[] buttonLabels = {"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"};
int x = 20, y = 80;
for (int i = 0; i < buttons.length; i++) {
5
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].setBounds(x, y, 50, 40);
add(buttons[i]);
x += 60;
if ((i + 1) % 4 == 0) {
x = 20;
y += 50;
buttons[i].addActionListener(new ButtonClickListener());
JButton historyButton = new JButton("History");
historyButton.setBounds(90, y + 50, 100, 40);
add(historyButton);
historyButton.addActionListener(e -> showHistory());
add(display);
setLayout(null);
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Calculator with History");
6
private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {
display.setText(display.getText() + command);
} else if (command.equals("C")) {
display.setText("");
num1 = num2 = result = 0;
operator = "";
} else if (command.equals("=")) {
num2 = Double.parseDouble(display.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
7
case "/":
result = num1 / num2;
break;
String expression = num1 + " " + operator + " " + num2;
display.setText(String.valueOf(result));
DatabaseConnection.saveCalculation(expression, String.valueOf(result));
} else {
num1 = Double.parseDouble(display.getText());
operator = command;
display.setText("");
private void showHistory() {
try {
JFrame historyFrame = new JFrame("Calculation History");
JTextArea historyArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(historyArea);
Connection conn = DatabaseConnection.connect();
var statement = conn.createStatement();
var resultSet = statement.executeQuery("SELECT * FROM CalculationHistory");
8
while (resultSet.next()) {
historyArea.append(
resultSet.getString("Expression") + " = " +
resultSet.getString("Result") + "\n");
historyFrame.add(scrollPane);
historyFrame.setSize(400, 300);
historyFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Calculator().setVisible(true);
});
```
---
9
### **7. Run and Test the Application**
1. Run the application by right-clicking the `main` method and selecting **Run File**.
2. Perform calculations and check the history in the database.
3. Click the **History** button to view stored calculations.
---
### **Features**
1. Performs basic arithmetic operations.
2. Stores calculation history in a MySQL database.
3. Displays history in a separate window.
You can enhance this project by adding additional features such as:
- Logging errors.
- Advanced functions like square root or percentage.
- Exporting history to a file.
10