Programming Examples

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

Radio JToggleButton Example

1. Radio ToggleButton

In Java Swing, we can make JToggleButton acting as a Radio Button. Just like in the previous example, we must create the JToggleButton and then assign that to the ButtonGroup. Doing so will make only one button in the group to switch to ON state. When a button is switched to ON state, all other buttons in the group go to the OFF state.

2. About the Example

The below screen shows the example:

Radio JToggleButton Example
Radio JToggleButton Example

In this example, we have seven JToggleButton components. First 4 is for the Nationality and second three is for the Sex. Here, these toggle buttons act like a radio button. One can also note that there are two groups here. In a group, only one toggle button can stay in Switched ON state. The above picture shows France and Female is in Selected State. Now, we will implement this example.

3. Create Button Groups

Since we need to group the Toggle Buttons in two groups, we create two ButtonGroup instances (Line 12,13). Later, we will add the ToggleButtons to this group just like what we do for the radio buttons.

4. Setup Radio JToggleButton

In code snippet 3, we create three JToggleButton and add that to our first button group. In code snippet 4, we do the same for the next set of JToggleButtons and group them under the Nationality ButtonGroup. Now, we have two set of Radio JToggleButton in our sample. As already told, in a group, user can keep only one JToggleButton in the selected state.

Finally, we add all the components to the content pane of the JFrame window.

5. Watch JToggleButton as Youtube

6. Code Reference


6.2 JToggleButtonAsRadio.Java

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.