Skip to content
Advertisement

How to get/set JRadionButtonMenuItem dynamically?

This example has Radio Buttons located on a Sub Menu as seen here.

enter image description here

What I would like to do is anytime the “Change Radio Button” button is pressed, it will change which button is selected on the menu. This means it has to first retrieve which is currently set then select the other.

Granted for this simple sample the Radio Buttons could be made instance variables to make things easy but image the JMenu and associated sub-menus and radio buttons are generated is some class further down in the bowels of the program. Direct access is not that direct.

JavaScript

It is not clear how best to access the sub-menu and associated radio button settings within the JButton action.

JavaScript

I could probably get the Menu Bar from the Frame and drill down figure the code can get messy if there Menu Bar has numerous items, sub items and even multiple radio button groups.

Is there a more direct way to find out which Radio Buttons on the menu are selected as well as a more direct way to change their value?

Advertisement

Answer

The “trick” is to create an application model to hold the value of the menu radio buttons.

Here’s the GUI I created.

MenuSample Example

I started the Swing application with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.

I created a JFrame and a JButton JPanel. I separated the creation of the JFrame and JPanel.

I created an application model class to hold a boolean which determines whether forward or backward is selected. The JButton ActionListener switches the state of the boolean. The updateRadioButtonMenu method updates the selected state of the radio button menu items.

Here’s the complete runnable code.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement