Java GUI (Graphical User Interface) Calculator Program

Learning to write a program that adds numbers is pretty easy but getting an interface working that does it can be difficult. Not only is interface programming difficult in itself, but there are a lot of considerations regarding proper program procedure. How do you store the numbers and clear the display at the right time, etc? Well I took a couple of hours to write a Java program utilizing swing, actionlistener enabled buttons, and layout managers, to get a working calculator. It is only useful for integers right now and decimal points will have to wait, but all the right ideas are there. Here’s the source code. Study it carefully to learn Java and calculator programming in general. Remember if you cut and paste to correct the double smart quotes by retyping them manually. Eclipse is high functioning enough that it pastes them from WordPress smartly, which is stupid. :) Enjoy!

//Simple Java Calculator Program by Jeremiah Embs of
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;

public class Calculator  implements ActionListener{//we are using ActionListener interface
//which allows buttons to work, but requires actionPerformed(ActionEvent e) method to
//be written to over-ride!
static boolean clsnext = false;//makes sure we clear the screen only when appropriate
static boolean flagfirstnumber = true;//makes sure we are storing the number correctly
static int a, b;//numbers to add or subtract etc.
static String operator = “”;//like PLUS, MINUS, etc.

static JPanel p2 = new JPanel();//declares a second panel to put in the window

static JTextField tf = new JTextField(30);//this is where our output displays

static JButton b0 = new JButton(“0”);//buttons
static JButton b1 = new JButton(“1”);
static JButton b2 = new JButton(“2”);
static JButton b3 = new JButton(“3”);
static JButton b4 = new JButton(“4”);
static JButton b5 = new JButton(“5”);
static JButton b6 = new JButton(“6”);
static JButton b7 = new JButton(“7”);
static JButton b8 = new JButton(“8”);
static JButton b9 = new JButton(“9”);
static JButton b10 = new JButton(“+”);
static JButton b11 = new JButton(“-“);
static JButton b12 = new JButton(“*”);
static JButton b13 = new JButton(“/”);
static JButton b14 = new JButton(“=”);
static JButton b15 = new JButton(“CLEAR”);

    public static void main(String[] args){
        Calculator c = new Calculator();//create an object of our own class for easy use
        //we could instead invoke eventually add.actionlistener(new Calculator())…
        //but that is calculation wasteful and all our field members (global variables)…
        //would always must be static or they would reset every time we clicked a button..
        //in the interface. I made them static none-the-less as this is correct practice…
        //for fields in the main class
        JFrame jf = new JFrame();//this creates a basic window object
        jf.setTitle(“JAVA CALCULATOR – BY JEREMIAH EMBS”);//setting up it’s parameters
        jf.setSize(340, 200);//size width height
        jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);//closes program when window closes
        JPanel p = new JPanel();//declares a panel to put in the window
        p.add(b0);//adding buttons to the panel
        b0.addActionListener(c);//adding an action listener to each of the buttons..
        b1.addActionListener(c);//we need to invoke c which is our Calculator()..
        b2.addActionListener(c);//object to listen to actions on that to make the..
        b3.addActionListener(c);//buttons work. We could have passed..
        b4.addActionListener(c);//new Calculator() but that is a hog…
        b5.addActionListener(c);//better to just make the one object and pass it
        b6.addActionListener(c);//into the add action listener class each time.
        Border border1 = BorderFactory.createRaisedBevelBorder();//border for…
        //a nicer appearance… not necessary..
        tf.setEditable(false);//we don’t want user to be able to type in the box.
        //It’s a cheap trick but it solves error handling if they entered a bad number
        //or a string or something
        jf.setLayout(new BorderLayout());//sets the basic layout north,east,west,south
        p.setLayout(new GridLayout(5,5,5,5));//first panel’s layout is 5 rows and columns, spaced 5,5
        p2.add(tf);//adds the textfield to the second panel
        jf.add(p, BorderLayout.NORTH);//fixes the first panel to the northside
        jf.add(p2, BorderLayout.CENTER);//fixes the second panel to the southside


    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == b0){//basic button for zero
            if (clsnext == true) cls();//clear the screen if equals was last…
            //button pushed
            tf.setText(tf.getText() + “0”);//adds the number zero to the display…
            //we do this as Strings and then convert to numbers before calculation
        if (e.getSource() == b1){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “1”);
        if (e.getSource() == b2){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “2”);
        if (e.getSource() == b3){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “3”);
        if (e.getSource() == b4){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “4”);
        if (e.getSource() == b5){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “5”);
        if (e.getSource() == b6){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “6”);
        if (e.getSource() == b7){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “7”);
        if (e.getSource() == b8){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “8”);
        if (e.getSource() == b9){
            if (clsnext == true) cls();
            tf.setText(tf.getText() + “9”);
        if (e.getSource() == b10){
            a = Integer.valueOf(tf.getText());//converts the number from a String to..
            // an int and stores the number in int a.
            tf.setText(“”);//clears the display without affecting the flag
            operator = “PLUS”;//changes the operator to plus
        if (e.getSource() == b11){
            a = Integer.valueOf(tf.getText());
            operator = “MINUS”;
        if (e.getSource() == b12){
            a = Integer.valueOf(tf.getText());
            operator = “MULTIPLY”;
        if (e.getSource() == b13){
            a = Integer.valueOf(tf.getText());
            operator = “DIVIDE”;
        if (e.getSource() == b14){
            b = Integer.valueOf(tf.getText());//converts & stores next number in int b
            if (operator.equalsIgnoreCase(“PLUS”)){
            tf.setText(String.valueOf(addNumbers()));//returns the sum of the numbers
            if (operator.equalsIgnoreCase(“MINUS”)){
            if (operator.equalsIgnoreCase(“MULTIPLY”)){
            if (operator.equalsIgnoreCase(“DIVIDE”)){
            clsnext = true;
            operator = “”;
        if (e.getSource() == b15){
    private int addNumbers() {
        return (a + b);
    private int divideNumbers() {
        return (a / b);
    private int multiplyNumbers() {
        return (a * b);
    private int subtractNumbers() {
        return (a – b);

    private void cls() {//clears the display and resets flag for clearing screen
        clsnext = false;
}//end of file