In the last article, we’ve already known how to use JFrame, JPanel and add components into your application. In this post, we’ll learn how to handle the button event, for example, display something, or change the text field content when the button is clicked.

This is the calculator we will make on this post

Starting code

First, we will make some change on the code from the last post:

//This code is credited to samderlust.com
import javax.swing.*;

public class GUICalculator extends JFrame {

    private JButton button1;
    private JTextField textField1;

    public static void main(String[] args) {
        GUICalculator cal = new GUICalculator();
        cal.setTitle("GUI Calculator");
        cal.setSize(600,400);
        cal.setVisible(true);
        cal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public GUICalculator () {
        JPanel panel1 = new JPanel();

        button1 = new JButton("button1");
        textField1 = new JTextField(20);

        panel1.add(button1);
        panel1.add(textField1);

        this.add(panel1);
    }
}

Now, we will have a window with just a button and a text field. Note that we declare the button1 and textField1 in the top so that we can use it everywhere later in the same class

Implement ActionListener interface

ActionListener is an interface that you can implement on a class to make a handler class that listens to the click event in a particular button to do something. Using an interface is another kind of Polymorphism when a class has only inherited the method and modify the method that suitable for its need.

There are several ways to implement this listener, but the common way is making a private handler class so that the code will be cleaner.  After the GUICalculator constructor, we declare a new private class.

private class ListenForButton implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
       if(e.getSource() == button1) {
           textField1.setText("This is from the button1");
       }
    }
}
  1. private class ListenForButton implements ActionListener define a new private class that implements the ActionListener interface. Since we just use this class inside the class of  GUICalculator to set the event handler for the button inside this JFame, we make it private.
  2. public void actionPerformed(ActionEvent e) we override the method ofactionPerformed the ActionListener interface, as we’re overriding it, the signature of the method (name, return type, parameter) must be kept the same. If a button that is added this listener is clicked, it will trigger an event and send it to this ActionListener and pass an ActionEvent object (in this case we named it “e”)to the methodactionPerformed as a parameter.
  3. if(e.getSource() == button1) then we will evaluate where the ActionEvent object come from by using the getSource() method of that ActionEvent object. If it comes from the button1, we will do something. Since we will add some more buttons, using if statement helps us to determine which is the button that triggered the event. Therefore we can give it the appropriate actions
  4. textField1.setText("This is from the button1"); As the event is trigger from the button1, we will set the Text of the textField1 “This is from the button1“.

But with this alone, your button doesn’t work yet, because currently the button1 is not added the ActionListioner. Let’s do it

Add ActionListener to a button

Adding this code right above where we add the button1 to the panel1 panel1.add(button1):

ListenForButton listenForButton = new ListenForButton();
button1.addActionListener(listenForButton);
  • First, we make a new object of the private class ListenForButton that we have just declared.
  • Second, we add the ActionListener to the button1

Run your program and click the button.

See the magic? give yourself a bravo!

Now are you ready to rock and roll? Let make your app a little bit more complex.

Add more button into the app

We make a simple application that add 2 number together. We will need the following components

  • 2 text fields for inputting number
  • 1 text field for displaying result
  • 4 buttons of operations

1. Declare more buttons and text fields in the class

private JButton button2;
private JButton button3;
private JButton button4;
private JTextField textField2;
private JTextField textField3;

2. Define the buttons and text fields

button1 = new JButton("+");
button2 = new JButton("-");
button3 = new JButton("*");
button4 = new JButton("/");
textField1 = new JTextField(20);
textField2 = new JTextField(20);
textField3 = new JTextField(20);

3. Add action listener to all the buttons

ListenForButton listenForButton = new ListenForButton();
button1.addActionListener(listenForButton);
button2.addActionListener(listenForButton);
button3.addActionListener(listenForButton);
button4.addActionListener(listenForButton);

4. Add all the buttons and text fields to the panel

panel1.add(textField1);
panel1.add(textField2);
panel1.add(textField3);

panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.add(button4);
Your app should look like this now

5. Rock the Action Listener

public void actionPerformed(ActionEvent e) {
    //1
    double number1 = 0;
    double number2 = 0;

    //2
    try {
        number1 = Double.parseDouble(textField1.getText());
        number2 = Double.parseDouble(textField2.getText());
    } catch (Exception error) {
        error.printStackTrace();
    }

    //3
    if (e.getSource() == button1) {
        textField3.setText(number1 + number2 + "");
    } else if (e.getSource() == button2) {
        textField3.setText(number1 - number2 + "");
    } else if (e.getSource() == button3) {
        textField3.setText(number1 * number2 + "");
    } else if (e.getSource() == button4) {
        textField3.setText(number1 / number2 + "");
    }
}

What we did in the code above:

  1. Declare 2 new double numbers and initial the value of them to 0;
  2. We use try catch to parse the content of the textfields1 and 2 int to double. The sake of using try catch here is if content is blank or text which are can’t parse into number our program wont be crashed.
  3. We will determine which is the button that is clicked to do the appropriate operation. I plus the empty string int the setText() method to cast everything into string.

Now, run your app and enjoy the hard work:

Full code:

//This code is credited to samderlust.com

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

public class GUICalculator extends JFrame {

    private JButton button1;
    private JTextField textField1;

    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JTextField textField2;
    private JTextField textField3;


    public static void main(String[] args) {
        GUICalculator cal = new GUICalculator();

        cal.setTitle("GUI Calculator");

        cal.setSize(600, 400);

        cal.setVisible(true);

        cal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public GUICalculator() {
        JPanel panel1 = new JPanel();

        button1 = new JButton("+");
        button2 = new JButton("-");
        button3 = new JButton("*");
        button4 = new JButton("/");
        textField1 = new JTextField(20);
        textField2 = new JTextField(20);
        textField3 = new JTextField(20);


        ListenForButton listenForButton = new ListenForButton();
        button1.addActionListener(listenForButton);
        button2.addActionListener(listenForButton);
        button3.addActionListener(listenForButton);
        button4.addActionListener(listenForButton);

        panel1.add(textField1);
        panel1.add(textField2);
        panel1.add(textField3);

        panel1.add(button1);
        panel1.add(button2);
        panel1.add(button3);
        panel1.add(button4);

        this.add(panel1);
    }

    private class ListenForButton implements ActionListener {


        @Override
        public void actionPerformed(ActionEvent e) {
            //1
            double number1 = 0;
            double number2 = 0;

            //2
            try {
                number1 = Double.parseDouble(textField1.getText());
                number2 = Double.parseDouble(textField2.getText());
            } catch (Exception error) {
                error.printStackTrace();
            }

            //3
            if (e.getSource() == button1) {
                textField3.setText(number1 + number2 + "");
            } else if (e.getSource() == button2) {
                textField3.setText(number1 - number2 + "");
            } else if (e.getSource() == button3) {
                textField3.setText(number1 * number2 + "");
            } else if (e.getSource() == button4) {
                textField3.setText(number1 / number2 + "");
            }
        }
    }
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here