2012-04-08 2 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); 

어떤 것을 선택했는지 어떻게 확인할 수 있습니까?

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를 먼저 설정 한 경우에만 작동합니다. 예컨대, :. 청취자가 연결된 경우

// 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

일에서하지만 http://tips4java.wordpress.com/2008/11/09/select-button (대릴의 [선택 버튼 그룹]에서 선택 라디오 버튼의 텍스트를 반환합니다 -group /),이 사람은 정말로 외계인이며, 사용자 정의 finalize(), bump를 구현합니다. – mKorbel

+0

@mKorbel 나는이 부분에서 Darryl이 더 많이 보았 더라면 좋겠습니다. –

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()); 
     } 
    }    
관련 문제