java中的单选按钮问题。为什么按其中一个按钮两个if语句中都运行

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
public class JRadio extends JFrame{

private JRadioButton bt1,bt2;
private ButtonGroup buttonG;
public JRadio()
{
super("JRadioButton Example");
Container c = getContentPane();
c.setLayout( new FlowLayout() );
bt1=new JRadioButton("aa",true);
bt2=new JRadioButton("bb",false);
c.add(bt1);
c.add(bt2);

bt1.addItemListener(new Handler1());
bt2.addItemListener(new Handler1());
buttonG = new ButtonGroup();
buttonG.add(bt1);
buttonG.add(bt2);

setSize(200,150);
setVisible(true);
}
public static void main(String args[])
{
JRadio app = new JRadio();
app.addWindowListener(new Handler2());
}
class Handler1 implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==bt1)
{ System.out.println("aa");}
else if(e.getSource()==bt2)
{ System.out.println("bb");}

}
}
static class Handler2 extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit( 0 );
}
}
}

你应该为bt1和bt2添加 addActionListener 监听
bt1.addActionListener(new Handler1());
bt2.addActionListener(new Handler1());

class Handler1 implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
{
if(e.getSource()==bt1)
{ System.out.println("aa");}
else if(e.getSource()==bt2)
{ System.out.println("bb");}

}
}
温馨提示:答案为网友推荐,仅供参考
相似回答