2012-04-08 58 views
3

我在ButtonGroup中有幾個JRadioButton。哪個JRadioButton選擇

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

如何確認選擇了哪一個?

With System.out.println(radioGroup.getSelection())我只得到類似[email protected]的東西。

回答

6

從選定的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時才起作用。 e.g。,:

// code not compiled, run, 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]); 
} 
3

如果聽衆所連接的簡單的方法來確定源是調用ActionEvent.getSource()

+2

+1但是從歐陽的[選擇按鈕組(http://tips4java.wordpress.com/2008/11/09/select-button返回所選擇的單選按鈕的文本-group /),編輯這個人真的是一個外星人,執行定製finalize(),碰撞... – mKorbel 2012-04-08 22:53:22

+0

@mKorbel我希望我看到更多(或任何,關於這個問題)Darryl周圍這些部分。 – 2012-04-08 22:59:19

0

這將從ButtonGroup的

Enumeration<AbstractButton> allRadioButton=radioGroup.getElements(); 
    while(allRadioButton.hasMoreElements()) 
    { 
     JRadioButton temp=(JRadioButton)allRadioButton.nextElement(); 
     if(temp.isSelected()) 
     { 
      JOptionPane.showMessageDialog(null,"You select : "+temp.getText()); 
     } 
    }