Creating Toggle Button with JToggleButton

In this tutorial, you will learn how to use JToggleButton class to create toggle buttons in Swing.

A toggle button is two-states button that allows user to switch on and off. To create a toggle button in Swing you use JToggleButton class.

Here are the most common used constructors of the JToggleButton class:

JToggleButton ConstructorsMeanings
public JToggleButton( )Creates a toggle button without text and icon. The state of toggle button is not selected.
public JToggleButton(Icon icon)Creates a toggle button with icon
public JToggleButton(Icon icon, boolean selected)Creates a toggle button with icon and initialize the state of toggle button by the boolean parameter selected
public JToggleButton(String text)Creates a toggle button with text
public JToggleButton(String text, boolean selected)Creates a toggle button with text and initialize  the state of the toggle button
public JToggleButton(String text, Icon icon)Creates a toggle button which displays both text and icon.
public JToggleButton(String text, Icon icon, boolean selected)Creates a toggle button which displays both text and icon. The state of toggle button can be initialized.

Example of using JToggleButton

In this example, we will create a simple toogle button by using the JToggleButton class. We will also add different event handlers to handle click event. A popup message will display whenever user clicks the button.

Here is the screenshot of the demo application:

JToggleButton Demo