Java JToggleButton with Example using NetBeans

Java JToggleButton

The implementation of a Java JToggleButton differs from the JButton in that the button can have two states: selected or not selected. If the Java JToggleButton was clicked or set to selected, the button gets a different background color so that you can see that it has been selected. If you click again, the appearance changes back to the initial state.


Java JToggleButton Constructors:

In addition to the standard constructor, the JToggleButton class has a few other constructors that we would like to explain in more detail in the following table.

Constructor Description
JToggleButton(Action a) Here, a Java JToggleButton is directly assigned an action that is to be triggered by clicking the button. We will go into more detail about actions later.
JToggleButton(Icon icon) This constructor creates a java JToggleButton with an Icon. This usage is very common in toolbars ( JToolBar ).
JToggleButton(String text) This constructor is used to set the text of the Java JToggleButton as a  label.
JToggleButton(String text, Icon icon) With the help of this constructor, both a text and an icon can be assigned to the Java JToggleButton. The text appears behind the icon.
JToggleButton(Icon icon, boolean selected) This constructor creates a java JToggleButton with an Icon. In addition, the status of the button is specified. If the value true is passed as the second parameter, the button has the status “pressed”.
JToggleButton(String text, boolean selected) Here a JToggleButton is created with a text as a label. In addition, the status of the button is specified. If the value true is passed as the second parameter, the button has the status “pressed”.
JToggleButton(String text, Icon icon, boolean selected) Here the previous constructor is extended by an icon.

The status of the JToggleButton can be queried using the isSelected function, which returns a boolean value (true for selected and false for unselected).



Example: how to use Java JToggleButton using NetBeans: 

I  have created a Java JToggleButton using the sixth constructor from the table above. Since I set the status to false via the second parameter, the button is displayed as unselected when the program starts. If you click on the button, the status changes to “selected”.


Screenshot of the unselected button:

Java JToggleButton

Screenshot of the selected button:

Java JToggleButton

As you can see, the button’s background color changes depending on the state.


Example: How to change Container Color using Java JToggleButton:

Output:

Java JToggleButton

Java JToggleButton

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: