JButton - Part 2

Event Listeners are the things that make the GUI come alive. When a user does anything to a GUI like re-size it, press a mouse button or enter text into a textfield, an 'event' will occur. We use an Event Listener to listen for certain events and edit the GUI on the occurrence of the event.

There are many different Event Listeners, each looking out for a specific type of event.

The Event Listener a JButton uses is an ActionListener. This covers the events created by Buttons, TextFields and MenuItems. In this tutorial we shall look at how to put one in practise for Buttons so you will be familiar with the concept when we cover the other widgets.

To show you how an Action Listener is used, we shall go back to the previous example of the Scoreboard.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ButtonExample_Extended implements  ActionListener{

    // Definition of global values and items that are part of the GUI.

    int redScoreAmount = 0;
    int blueScoreAmount = 0;

    JPanel titlePanel, scorePanel, buttonPanel;
    JLabel redLabel, blueLabel, redScore, blueScore;
    JButton redButton, blueButton, resetButton;

    public JPanel createContentPane (){

        // We create a bottom JPanel to place everything on.
        JPanel totalGUI = new JPanel();
        totalGUI.setLayout(null);

        // Creation of a Panel to contain the title labels
        titlePanel = new JPanel();
        titlePanel.setLayout(null);
        titlePanel.setLocation(10, 0);
        titlePanel.setSize(250, 30);
        totalGUI.add(titlePanel);

        redLabel = new JLabel("Red Team");
        redLabel.setLocation(0, 0);
        redLabel.setSize(120, 30);
        redLabel.setHorizontalAlignment(0);
        redLabel.setForeground(Color.red);
        titlePanel.add(redLabel);

        blueLabel = new JLabel("Blue Team");
        blueLabel.setLocation(130, 0);
        blueLabel.setSize(120, 30);
        blueLabel.setHorizontalAlignment(0);
        blueLabel.setForeground(Color.blue);
        titlePanel.add(blueLabel);

        // Creation of a Panel to contain the score labels.
        scorePanel = new JPanel();
        scorePanel.setLayout(null);
        scorePanel.setLocation(10, 40);
        scorePanel.setSize(260, 30);
        totalGUI.add(scorePanel);

        redScore = new JLabel(""+redScoreAmount);
        redScore.setLocation(0, 0);
        redScore.setSize(120, 30);
        redScore.setHorizontalAlignment(0);
        scorePanel.add(redScore);

        blueScore = new JLabel(""+blueScoreAmount);
        blueScore.setLocation(130, 0);
        blueScore.setSize(120, 30);
        blueScore.setHorizontalAlignment(0);
        scorePanel.add(blueScore);

        // Creation of a Panel to contain all the JButtons.
        buttonPanel = new JPanel();
        buttonPanel.setLayout(null);
        buttonPanel.setLocation(10, 80);
        buttonPanel.setSize(260, 70);
        totalGUI.add(buttonPanel);

        // We create a button and manipulate it using the syntax we have
        // used before. Now each button has an ActionListener which posts 
        // it's action out when the button is pressed.

        redButton = new JButton("Red Score!");
        redButton.setLocation(0, 0);
        redButton.setSize(120, 30);
        redButton.addActionListener(this);
        buttonPanel.add(redButton);

        blueButton = new JButton("Blue Score!");
        blueButton.setLocation(130, 0);
        blueButton.setSize(120, 30);
        blueButton.addActionListener(this);
        buttonPanel.add(blueButton);

        resetButton = new JButton("Reset Score");
        resetButton.setLocation(0, 40);
        resetButton.setSize(250, 30);
        resetButton.addActionListener(this);
        buttonPanel.add(resetButton);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // This is the new ActionPerformed Method.
    // It catches any events with an ActionListener attached.
    // Using an if statement, we can determine which button was pressed
    // and change the appropriate values in our GUI.

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == redButton)
        {
            redScoreAmount = redScoreAmount + 1;
            redScore.setText(""+redScoreAmount);
        }
        else if(e.getSource() == blueButton)
        {
            blueScoreAmount = blueScoreAmount + 1;
            blueScore.setText(""+blueScoreAmount);
        }
        else if(e.getSource() == resetButton)
        {
            redScoreAmount = 0;
            blueScoreAmount = 0;
            redScore.setText(""+redScoreAmount);
            blueScore.setText(""+blueScoreAmount);
        }
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JButton Scores! [=]");

        //Create and set up the content pane.
        ButtonExample_Extended demo = new ButtonExample_Extended();
        frame.setContentPane(demo.createContentPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(280, 190);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
You should compile this program and run it on your own system. It should look like this.

Picture of Buttons

However, when you push the "Red Scores" button, the Red Score will go up by 1. The "Blue Scores" button will increment the blue score by 1 and the reset button sets both scores back to 0. How do we achieve that?

The first thing to notice is that our class now implements ActionListener so that we may create an actionPerformed method that reacts to events on the GUI.
6
public class ButtonExample_Extended implements  ActionListener{
We define the buttons, panels and labels outside of the createContentPane() method. This way they are now proper class objects so that the ActionListener knows they exist. We also define two integers that will keep track of the scores for each team.
10
11
12
13
14
15
    int redScoreAmount = 0;
    int blueScoreAmount = 0;

    JPanel titlePanel, scorePanel, buttonPanel;
    JLabel redLabel, blueLabel, redScore, blueScore;
    JButton redButton, blueButton, resetButton;
You will notice there is not a great deal of extra code when creating the widgets for the GUI. The buttons, because they are user driven, receive ActionListeners (Line 77). This means that when they are pressed, the event will be sent to the ActionPerformed method.
74
75
76
77
78
        redButton = new JButton("Red Score!");
        redButton.setLocation(0, 0);
        redButton.setSize(120, 30);
        redButton.addActionListener(this);
        buttonPanel.add(redButton);
At this time, it is worth mentioning a little about the keyword 'this'. As you can see in Line 77, when you do addActionListener(), it takes in the argument 'this'. Normally, the argument of addActionListener is an ActionListener. Why do we use the keyword 'this'?

'this' is a keyword that lets you reference the object you are currently in.
So, the object you are currently in is the 'ButtonExample_Extended' object, which is the name of the current class. This class implements ActionListener. So, by using the keyword 'this', we can use the default ActionListener of the class.

This also means when you get quite good at Swing, you can define your own Event Listeners to behave differently than the default one. For now though, let's just stick to the default Event Listener that is implemented in the class.
77
        redButton.addActionListener(this);
When an event occurs on a widget that has an ActionListener, the ActionPerformed method is called and takes the event as an argument.
Then, with the aid of an 'if ' statement, we determine which button was actually pressed by using .getSource(). Once we know this information, we can carry out an action based on the event.

If the redButton is pressed, as you can see, the redScoreAmount value is incremented by 1 and displayed on the redScore JLabel. The same happens with the blue. If the reset button is pressed, both values are set to 0.
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == redButton)
        {
            redScoreAmount = redScoreAmount + 1;
            redScore.setText(""+redScoreAmount);
        }
        else if(e.getSource() == blueButton)
        {
            blueScoreAmount = blueScoreAmount + 1;
            blueScore.setText(""+blueScoreAmount);
        }
        else if(e.getSource() == resetButton)
        {
            redScoreAmount = 0;
            blueScoreAmount = 0;
            redScore.setText(""+redScoreAmount);
            blueScore.setText(""+blueScoreAmount);
        }
    }
The only other syntax you might not know in this segment is the .setText() method. This sets the text of the JLabel.

This is a basic ActionListener. You will see these in further use in later programs. ActionListeners are only used for JButtons, JTextFields and JMenus. There are different Listeners used for different widgets.

The best way to practise this is to have a go yourself. It is recommended you have a go at the following exercise.

Exercises
Add a third team to the scoreboard, the Yellow team. The Yellow team is special, they receive 3 points every time they score.
Create label, button and score variable, and edit your actionListener to perform this task.

Exercise Hint
Exercise Example Code

Questions

Next is JToggleButton, but before that answer these questions...

Question 1. The String passed as an argument during the instantiation of a JButton is for?

  • a) The text displayed as a label beside the button.
  • b) The text displayed on the button.
  • c) The text displayed above the button.

Question 2. An Event Listener is ___ by the class.

  • a) Extended
  • b) Implemented
  • c) Copied

Question 3. What Event Listener does the JButton use?

  • a) ActionListener
  • b) ItemListener
  • c) FocusListener

Question 4. Why do we use the keyword 'this' as an argument of addActionListener()?

  • a) To loop back to the start of the widget.
  • b) To make the ActionListener a class variable.
  • c) To reference the default ActionListener of the current class.

Question 5. From the event, how do we find which button was pressed?

  • a) e.getSource();
  • b) e.whichSource();
  • c) e.whatSource();




Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict