In this tutorial

You will learn how to...
  • How to create a JButton.
  • To understand what an Event Listener is.
  • How to add an ActionListener to a JButton.
  • How to make your GUI change on a Button press.
  • To understand the difference between a Button and a ToggleButton.
  • How to add an ItemListener to a JToggleButton.

JButton - Part 1

This is a very short tutorial on the creation of JButtons. JButtons are just as you'd think, buttons on the screen that your user can press to change properties of your program.

We need to move onto a brand new example now. Technically JPanels shouldn't be used as a widget, they are widget containers. Now we have enough widgets to create a half decent program, for this tutorial we shall do away with our coloured box example.

In this example, we create a scoreboard for Red Team v Blue Team.
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
import javax.swing.*;
import java.awt.Color;

public class ButtonExample{

    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
        JPanel titlePanel = new JPanel();
        titlePanel.setLayout(null);
        titlePanel.setLocation(10, 0);
        titlePanel.setSize(250, 30);
        totalGUI.add(titlePanel);

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

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

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

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

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

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

        // We create a button and manipulate it using the syntax we have
        // used before.

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

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

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

    private static void createAndShowGUI() {

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

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

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 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();
            }
        });
    }
}
When run, the program should look like this.

Picture of Button Scoreboard

The layout of the widgets are based around three JPanels, one for the titles, one for the scores and one for the JButtons at the bottom.

We first create our JPanels. They are all of this format, albeit with different sizes and locations. If you want to see them a little easier, add a background colour to each as you have been taught in previous tutorials.
13
14
15
16
17
        JPanel titlePanel = new JPanel();
        titlePanel.setLayout(null);
        titlePanel.setLocation(10, 0);
        titlePanel.setSize(250, 30);
        totalGUI.add(titlePanel);
The creation of the labels is getting quite advanced, but still understandable.
19
20
21
22
23
24
        JLabel redLabel = new JLabel("Red Team");
        redLabel.setLocation(0, 0);
        redLabel.setSize(100, 30);
        redLabel.setHorizontalAlignment(0);
        redLabel.setForeground(Color.red);
        titlePanel.add(redLabel);
From the JLabel tutorial, you should know that setting the foreground colour changes the text to the colour in the argument.

We continue on, and create some buttons for the bottom of the application. One to add a point to the Red Team, one to add a point to the Blue Team and one to reset the scores.
62
63
64
65
        JButton redButton = new JButton("Red Score!");
        redButton.setLocation(0, 0);
        redButton.setSize(100, 30);
        buttonPanel.add(redButton);
As you can see, there is nothing very special about the creation of buttons. The string passed as an argument is the text displayed on the button itself.

One thing you may have noticed though is when you press a button, nothing happens! For a button to react to anything on the screen, the system needs to listen to the button for any changes. For this to occur, an ActionListener needs to be put in place.

Luckily for you, that will be our next section!

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