The JToggleButton Class

JToggleButton is an extension of AbstractButton and is used to represent buttons that can be toggled on and off (as opposed to buttons like JButton which, when pushed, “pop back up”). It should be noted that while the subclasses of JToggleButton (JCheckBox and JRadioButton) are the kinds of JToggleButtons most commonly used, JToggleButton is not an abstract class. When used directly, it typically (though this is ultimately up to the L&F) has the appearance of a JButton that does not pop back up when pressed.

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class JToggleButtonEvents {
	public static void main(String[] args) {
		JToggleButton jtb = new JToggleButton("Press Me");

		jtb.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ev) {
				System.out.println("ActionEvent!");
			}
		});
		jtb.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent ev) {
				System.out.println("ItemEvent!");
			}
		});
		jtb.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent ev) {
				System.out.println("ChangeEvent!");
			}
		});
		JFrame f = new JFrame();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = f.getContentPane();
		c.setLayout(new FlowLayout());
		c.add(jtb);
		f.pack();
		f.setVisible(true);
	}
}