加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 选择哪个JRadioButton

发布时间:2020-12-15 04:57:19 所属栏目:Java 来源:网络整理
导读:我在ButtonGroup中有几个JRadioButtons. private ButtonGroup radioGroup= new ButtonGroup(); private JRadioButton radio1= new JRadioButton("Red"); private JRadioButton radio2= new JRadioButton("Green"); private JRadioButton radio3= new JRadioB
我在ButtonGroup中有几个JRadioButtons.

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);

如何查看选择了哪一个?
使用System.out.println(radioGroup.getSelection())我只得到类似javax.swing.JToggleButton $ToggleButtonModel@32b3714的内容.

解决方法

从选定的ButtonModel中,您可以获取actionCommand String(如果您记得设置它!).

// code not compiled,run,nor tested in any way
ButtonModel model = radioGroup.getSelection();
String actionCommand = (model == null) ? "" : model.getActionCommand():
System.out.println(actionCommand);

但这只有在您首先设置actionCommand时才有效.例如.,:

// 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]);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读