Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JToggleButton as Two-State Button

1. JToggleButton Introduction

In Java Swing, the JToggleButton is a two-state button. Here, the two states are On and Off. When the user clicks the button, it toggles between this ON & OFF state. JToggleButton component is the base class for the JCheckBox and JRadioButton. Hence, the JToggleButton will raise an ItemEvent which we can handle via the ItemListener.

2. About The Example

The below picture shows the Java Swing’s JToggleButton (Two-State Button) Example:

Two-State Button Example
The below picture shows the Java Swing’s JToggleButton Example:

The example contains three components. One is a JLabel which tells in what mode the example is in. The button labelled OFF is the JToggleButton and it will switch the state between Selected & Unselected. The text box tells what kind of the state change is made by the user while he/she clicked the Two-State button last time.

3. Create JToggleButton as Two-State Button

At code snippet 2, we create JTextField with 30-character width and then we create JLabel. The JLabel will show the initial text “Write Mode”. We will change this text based on the JToggleButton state. In code snippet 3, we create the JToggleButton and to the constructor we pass the string “ON” and Java Swing will display this when the frame is displayed for the first time to the user. Finally, we add all these three components to the JFrame which is managed by the FlowLayout.

4. Handle ItemEvent of Two-State Button

The JToggleButton will raise an ItemEvent when the user clicks it. Method itemStateChanged of the ItemListener will handle this event and in the below code we use the anonymous inner class and provide the handler function implementation. The method isSelected of the JToggleButton tells whether it is in selected state (ON) or not.

In our handler function, we use this isSelected function and its return value to form the if condition. When the JToggleButton is in the selected state, we set the button text as “OFF” and when the button is not in the selected state we set the button text as “ON”. Also note, we report the item state change event in the text box as well.

5. Youtube Demo

6. Code Reference



Categories: Swing

Tags: , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.