Skip to content

“This Java Calculator Looks Like It’s From the Future (No JavaFX Needed!)”


🧠 What You’ll Learn:

In this tutorial, we’re going to build a simple yet sleek Java calculator using Swing! Forget JavaFX — this app will use only Java Swing to create an interface that looks modern and runs smoothly. You’ll learn:

  • How to design an intuitive GUI with Swing.
  • Event handling using buttons for input and calculations.
  • Handling operations like addition, subtraction, multiplication, and division.
  • Designing a calculator that looks like it belongs in Windows 11 — modern, clean, and minimal.

🛠️ Project Overview:

FeatureTech Used
GUI LayoutJava Swing
Button HandlingActionListeners
Arithmetic LogicBasic Operations
Design StyleWindows 11-inspired Minimalism

📁 File Structure:

For simplicity, we’ll keep everything in a single Java file:

CalculatorApp.java

🧾 Full Source Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CalculatorApp extends JFrame {
    private JTextField display;

    public CalculatorApp() {
        // Set up the frame
        setTitle("Java Calculator");
        setSize(350, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLookAndFeel();

        // Initialize display
        display = new JTextField();
        display.setEditable(false);
        display.setFont(new Font("Arial", Font.PLAIN, 24));
        display.setHorizontalAlignment(SwingConstants.RIGHT);

        // Set up the button panel
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(5, 4, 10, 10));

        // Define buttons
        String[] buttonLabels = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        };

        for (String label : buttonLabels) {
            JButton button = new JButton(label);
            button.setFont(new Font("Arial", Font.PLAIN, 24));
            button.setFocusPainted(false);
            button.addActionListener(new ButtonClickListener());
            buttonPanel.add(button);
        }

        // Set up the clear button
        JButton clearButton = new JButton("C");
        clearButton.setFont(new Font("Arial", Font.PLAIN, 24));
        clearButton.setFocusPainted(false);
        clearButton.addActionListener(e -> display.setText(""));
        buttonPanel.add(clearButton);

        // Add components to the frame
        add(display, BorderLayout.NORTH);
        add(buttonPanel, BorderLayout.CENTER);

        setVisible(true);
    }

    private void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ButtonClickListener implements ActionListener {
        private StringBuilder input = new StringBuilder();

        @Override
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();

            if (command.equals("=")) {
                try {
                    input.append("=").append(eval(input.toString()));
                    display.setText(input.toString());
                } catch (Exception ex) {
                    display.setText("Error");
                }
            } else {
                input.append(command);
                display.setText(input.toString());
            }
        }

        private double eval(String expression) {
            // Simple evaluation logic using basic arithmetic
            try {
                String[] tokens = expression.split(" ");
                double num1 = Double.parseDouble(tokens[0]);
                String operator = tokens[1];
                double num2 = Double.parseDouble(tokens[2]);

                switch (operator) {
                    case "+": return num1 + num2;
                    case "-": return num1 - num2;
                    case "*": return num1 * num2;
                    case "/": return num1 / num2;
                    default: return 0;
                }
            } catch (Exception e) {
                return 0;
            }
        }

        private void clearInput() {
            input.setLength(0);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new CalculatorApp());
    }
}

🧠 Code Breakdown (Line-by-Line)

1. import javax.swing.*; and import java.awt.*;

  • These imports bring in the classes needed for Swing GUI components and layout management.

2. public class CalculatorApp extends JFrame {

  • The main CalculatorApp class extends JFrame, making it a window-based application.

3. private JTextField display;

  • The JTextField named display will show the input and results of the calculations.

4. public CalculatorApp() {

  • Constructor to set up the frame and GUI components (buttons, layout, etc.).

5. setTitle("Java Calculator");

  • Sets the window title to Java Calculator.

6. setSize(350, 500);

  • Specifies the size of the window.

7. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  • Ensures the application closes when the user clicks the “X” button.

8. setLocationRelativeTo(null);

  • Centers the window on the screen.

9. setLookAndFeel();

  • Applies the system’s default look and feel, making the app’s UI blend in with the OS.

10. display = new JTextField();

  • Initializes the JTextField for displaying calculations.

11. display.setEditable(false);

  • Makes the display read-only, so users can’t edit directly.

12. display.setFont(new Font("Arial", Font.PLAIN, 24));

  • Sets the font and size of the text in the display to be clear and large.

13. JPanel buttonPanel = new JPanel();

  • Creates a new panel that will hold the calculator buttons.

14. buttonPanel.setLayout(new GridLayout(5, 4, 10, 10));

  • Uses a GridLayout with 5 rows and 4 columns for buttons, plus 10-pixel gaps between them.

15. String[] buttonLabels = {...};

  • An array holding the labels for all the buttons (numbers and operators).

16. for (String label : buttonLabels) {

  • Loops through each label and creates a JButton for each.

17. button.addActionListener(new ButtonClickListener());

  • Attaches an event listener to each button, which handles clicks.

18. JButton clearButton = new JButton("C");

  • Creates a button for clearing the display.

19. clearButton.addActionListener(e -> display.setText(""));

  • Clears the text in the display when clicked.

20. add(display, BorderLayout.NORTH);

  • Adds the display to the top (North) of the window.

21. add(buttonPanel, BorderLayout.CENTER);

  • Adds the button panel to the center of the window.

22. private class ButtonClickListener implements ActionListener {

  • This is the event handler class for the button clicks.

23. private StringBuilder input = new StringBuilder();

  • A StringBuilder is used to accumulate the user input for calculation.

24. @Override public void actionPerformed(ActionEvent e) {

  • Handles button clicks. If the “=” button is clicked, it evaluates the expression; otherwise, it appends the button label to the input.

25. private double eval(String expression) {

  • A basic evaluation method to process simple arithmetic expressions using the split() method for tokenizing and switch for operation logic.

26. public static void main(String[] args) {

  • The main method initializes the app using SwingUtilities.invokeLater() to ensure thread-safety with Swing components.

🧪 How to Run:

javac CalculatorApp.java
java CalculatorApp

💡 Bonus Ideas to Level Up:

  • Keyboard Support: Add support for keyboard input.
  • History: Track the calculation history.
  • Scientific Mode: Add functions like sine, cosine, etc.
  • Themes: Allow users to toggle between light and dark themes.

✍️ Final Thoughts:

Building this Java Swing Calculator is a great way to dive into GUI development while keeping things simple. With just a few lines of code, you can create an app that looks like it was designed with modern operating systems in mind. Whether you’re a beginner or an intermediate Java developer, this project is a perfect way to practice the basics and challenge yourself to make the UI as clean and functional as possible.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *