Java Swing – JToggleButton

A useful variation on the push button is called a Toggle Button. A toggle button looks just like a push button, but it acts differently because it has two states:
1. Pushed
2. Released

When you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles between its two states.

Toggle buttons are objects of the JToggleButton class. JToggleButton implements AbstractButton.
In addition to creating standard toggle buttons, JToggleButton is a superclass for two other Swing components that also represent two-state controls, These are JCheckBox and JRadioButton. JToggleButton defines several constructors:

JToggleButton(String str)

This creates a toggle button that contains the text passed in str. By default, the button is in the off position. Other constructors enable you to create toggle buttons that contain images, or images and text.

Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ToggleButton extends JApplet
{
JLabel jlab;
JToggleButton jtbn;
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch (Exception exc)
{
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
setLayout(new FlowLayout());
jlab = new JLabel("Button is off.");
jtbn = new JToggleButton("On/Off");
jtbn.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ie)
{
if(jtbn.isSelected())
jlab.setText("Button is on");
else
jlab.setText("Button is off");
}
});
add(jtbn);
add(jlab);
}
}