2013-01-31 121 views
1

我在我的swing應用程序上有5個JRadio按鈕。當我點擊我的Jradio按鈕。我創建了一個指示對話來顯示它被點擊。但是當我取消選擇它時,它也會顯示它被選中。問題是什麼? 我的Jradio按鈕編碼之一。如何顯示JRadio按鈕被選中和取消選擇?

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

所以,我終於得到了回答

與@Neil Locketz幫助

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

感謝

+0

有了這段代碼,很難說出是怎麼回事。 –

+0

如果Neil幫助你,請upvote並接受他的回答。 – 2013-01-31 13:41:23

回答

1

您需要選擇JRadioButton對象的引用,所以你可以調用button.isSelected( )這將返回一個布爾值,判斷您正在測試的按鈕是否被選中。

2
+0

+1來挖掘問題。雖然,這裏沒有毒性,因爲OP使用的是ActionListener,而不是ItemListener。另一方面:這只是巧合 - 因爲聽衆通知序列沒有保證。所以另一個(虛擬:-) +1仔細考慮invokeLater! – kleopatra

0

請記住,這是完全僞代碼

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