2013-01-31 2 views
1

내 스윙 애플리케이션에 5 개의 JRadio 버튼이 있습니다. 내 Jradio 버튼을 클릭하면 클릭 대화 상자를 만들어 대화 상자에 표시했습니다. 그러나 선택을 취소하면 선택한 것으로 표시됩니다. 문제가 무엇입니까? 내 Jradio 버튼 코딩 중 하나입니다. JRadio 버튼이 선택되고 선택 해제 된 것을 보여주는 방법은 무엇입니까?

 private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) 
{ 
     JOptionPane.showMessageDialog(null,"one is selected"); 
} 

그래서 나는 마지막으로 당신이 button.isSelected을 (호출 할 수 있도록 당신은 JRadioButton의 개체에 대한 참조를 필요

+0

그 코드를 사용하면 진행 상황을 알 수 없습니다. –

+0

Neil이 도움이 되었다면, 그의 대답을 upvote하고 수락하십시오. 문제를 파헤 치기 위해 –

답변

1

 private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) 
    { 
     if(jRadioButton1.isSelected()) 
      { 
      JOptionPane.showMessageDialog(null,"one is selected"); 
      } 
    } 

감사 @Neil Locketz의 도움으로

답변을 얻었다) 이것은 테스트중인 버튼이 선택되었는지 여부에 대한 부울을 반환합니다.

2
+0

+1. OP가 ItemListener가 아닌 ActionListener를 사용하기 때문에 여기서는 독성이 없습니다. 다른 한편으로는 그것은 단지 우연 일뿐입니다. 리스너 알림 시퀀스에 대한 보장이 없기 때문입니다. invokeLater를주의 깊게 생각한 또 다른 (가상 :-) +1! – kleopatra

0

염두에 두어야한다 JOptionPane

  • invokeLater() 내부에 표시하기위한이 이벤트를 지연 완전히 의사 코드

     JRadioButton testButton1=new JRadioButton("button1"); 
        JRadioButton testButton2=new JRadioButton("button2"); 
    
        ButtonGroup btngroup=new ButtonGroup(); 
    
        btngroup.add(testButton1); 
        btngroup.add(testButton2); 
    
        boolean test; 
    
        foreach(JRadioButton b in btngroup){ 
         test = b.isSelected(); 
         if(test) 
          JOptionPane.showMessageDialog(null, b.getValue() + "is selected"); 
        } 
    
  • 0

    단일 ActionListener 인스턴스를 만들어 모든 버튼에 추가하는 것이 좋습니다. 다음과 같은 것 :

    ButtonGroup group = new ButtonGroup(); 
    JRadioButton radio = new JRadioButton("1"); 
    JRadioButton radio2 = new JRadioButton("2"); 
    JRadioButton radio3 = new JRadioButton("3"); 
    group.add(radio); 
    group.add(radio2); 
    group.add(radio3); 
    ActionListener a = new ActionListener() { 
        public void actionPerformed(ActionEvent e) { 
         JRadioButton source = (JRadioButton) e.getSource(); 
         System.out.println(source.getText() + " selected " + source.isSelected()); 
        } 
    }; 
    radio.addActionListener(a); 
    radio2.addActionListener(a); 
    radio3.addActionListener(a);