Java – which JRadioButton to select
•
Java
I have several jradiobuttons in the button group
private ButtonGroup radioGroup= new ButtonGroup(); private JRadioButton radio1= new JRadioButton("Red"); private JRadioButton radio2= new JRadioButton("Green"); private JRadioButton radio3= new JRadioButton("Blue"); radioGroup.add(radio1); radioGroup.add(radio2); radioGroup.add(radio3);
How do I see which one is selected? Use system out. Println (radiogroup. Getselection()) I only get something like javax swing. JToggleButton $ ToggleButtonModel@32b3714 The content of the
Solution
From the selected buttonmodel, you can get the actioncommand string (if you remember to set it!)
// code not compiled,run,nor tested in any way ButtonModel model = radioGroup.getSelection(); String actionCommand = (model == null) ? "" : model.getActionCommand(): System.out.println(actionCommand);
But this only works if you first set actioncommand For example
// code not compiled,nor tested in any way String[] colors = {"Red","Green","Blue"}; JRadioButton[] radioBtns = new JRadioButton[colors.length]; for (int i = 0; i < radioBtns.length; i++) { radioBtns[i] = new JRadioButton(colors[i]); radioBtns[i].setActionCommand(colors[i]); radioGroup.add(radioBtns[i]); somePanel.add(radioBtns[i]); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码