import javax.swing.*;
import java.awt.event.*;class  JRadioButtonDemo implements ActionListener
{
private JFrame jframe;
private JPanel jpl;
private JRadioButton jrb1,jrb2,jrb3,jrb4;
private JLabel jlb;
private ButtonGroup bg;
public JRadioButtonDemo() 
{
jframe=new JFrame("JRadioButton Demo");
jpl = new JPanel();
jlb= new JLabel("Please choose your answer");
bg = new ButtonGroup(); jrb1 = new JRadioButton("A");
jrb1.addActionListener(this);
jpl.add(jrb1); jrb2 = new JRadioButton("B");
jrb1.addActionListener(this);
jpl.add(jrb2); jrb3 = new JRadioButton("C");
jrb1.addActionListener(this);
jpl.add(jrb3); jrb4 = new JRadioButton("D");
jrb1.addActionListener(this);
jpl.add(jrb4); bg.add(jrb1);bg.add(jrb2);bg.add(jrb3);bg.add(jrb4); jpl.add(jlb);
jframe.getContentPane().add(jpl);
jframe.pack();
jframe.setVisible(true);
jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
} public void actionPerformed(ActionEvent e)
{
jlb.setText("You choose the answer:"+e.getActionCommand());
}
public static void main(String[] args) 
{
new JRadioButtonDemo();
}
}
我运行后得出的结果不太对,只有点A时有反映,那里错了,谢谢

解决方案 »

  1.   

    加监听器的对象不对吧,全加到jrb1上去了
    应该为
    jrb1 = new JRadioButton("A");
    jpl.add(jrb1);
    jrb1.addActionListener(this);jrb2 = new JRadioButton("B");
    jpl.add(jrb2);
    jrb2.addActionListener(this);jrb3 = new JRadioButton("C");
    jpl.add(jrb3);
    jrb3.addActionListener(this);jrb4 = new JRadioButton("D");
    jpl.add(jrb4);
    jrb4.addActionListener(this);
      

  2.   

    jrb1 = new JRadioButton("A");
    jrb1.addActionListener(this);
    jpl.add(jrb1);jrb2 = new JRadioButton("B");
    jrb1.addActionListener(this);
    jpl.add(jrb2);jrb3 = new JRadioButton("C");
    jrb1.addActionListener(this);
    jpl.add(jrb3);jrb4 = new JRadioButton("D");
    jrb1.addActionListener(this);
    jpl.add(jrb4);
    ==================addActionListener() 方法统统加到“ jrb1”上了 ctrl+c ctrl+v的后遗症!!