JButton - Part 3 - The JToggleButton

An interesting version of the JButton is the JToggleButton. When you press a ToggleButton it stays on until you switch it off again. Because of this, it uses a different listener to the one we use for a JButton as it maintains a state of 'Selected' or 'Deselected'.

The Event Listener used in this case is an Item Listener. In this small example we show how a JToggleButton is instantiated just like a normal JButton, but with a different method for catching events.
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
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class ToggleButtonExample implements  ItemListener{

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

    JToggleButton toggleButton;
    JPanel totalGUI;

    public JPanel createContentPane (){

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

        toggleButton = new JToggleButton("Off");
        toggleButton.setLocation(75,10);
        toggleButton.setSize(100,100);
        toggleButton.addItemListener(this);
        totalGUI.add(toggleButton);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // This is the new itemStateChanged Method.
    // It catches any events with an ItemListener attached.
    // Using an if statement, we can determine if the button is now selected or deselected
	// after the action and perform changes to the GUI accordingly.

    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED)
        {
            toggleButton.setText("On!");
            totalGUI.setBackground(Color.green);
        }
        else
        {
            toggleButton.setText("Off");
            totalGUI.setBackground(Color.red);
        } 
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JToggleButton [=]");

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

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 150);
        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();
            }
        });
    }
}
As has been mentioned before, the JToggleButton has two states, Selected or Deselected.

Picture of a ToggleButton

We begin by making sure both the import statements and the class now deal with ItemListeners instead of ActionListeners.
1
2
3
4
5
6
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class ToggleButtonExample implements  ItemListener{
We instantiate the JToggleButton just like a normal button, with the String argument being passed as the string in the middle of the button.
Also, see that the command used is now .addItemListener() rather than .addActionListener().
20
21
22
23
24
        toggleButton = new JToggleButton("Off");
        toggleButton.setLocation(75,10);
        toggleButton.setSize(100,100);
        toggleButton.addItemListener(this);
        totalGUI.add(toggleButton);
The method used for Item Events is itemStateChanged(). Because there is only one button on the GUI, there is no point in finding out where the event came from, there is only one source with an item listener attached. We simply find the state of the item and change the GUI depending on the answer.
35
36
37
38
39
40
41
42
43
44
45
46
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED)
        {
            toggleButton.setText("On!");
            totalGUI.setBackground(Color.green);
        }
        else
        {
            toggleButton.setText("Off");
            totalGUI.setBackground(Color.red);
        } 
    }
The rest of the code is exactly the same as before. JToggleButtons are useful, but there are plenty of widgets that we cover in the future that are also very handy for determining state. (CheckBoxes, RadioButtons etc).

Questions

Tell me about the Toggle!

Question 1. Why is a JToggleButton different to a JButton?

  • a) It is a different shape.
  • b) It has four states, none, on, off, all.
  • c) It has two states, on and off.

Question 2. What Event Listener does the JToggleButton use?

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

Question 3. Hw do we find out if the ToggleButton is being selected or deselected?

  • a) e.getStateChange()
  • b) e.selectedOrDeselected()
  • c) e.getOtherSelection()




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