【发布时间】:2014-03-01 06:56:51
【问题描述】:
我只是在学习单选按钮,并认为我终于掌握了它,因为它编译得很好。但是当我尝试运行程序时,出现了这个错误:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1090)
at java.awt.Container.add(Container.java:410)
at ActionFrame.makeComponents(ActionFrame.java:43)
at ActionFrame.<init>(ActionFrame.java:20)
at ActionFrame.main(ActionFrame.java:80)
我不知道我做错了什么,所以如果你能指出我正确的方向吗?或者向我解释为什么我做错了?
public class ActionFrame extends JFrame {
JLabel messageLabel;
JRadioButton rb1;
JRadioButton rb2;
JRadioButton rb3;
JRadioButton rb4;
String a = "Football";
String b = "Basketball";
String c = "Baseball";
String d = "Hockey";
public ActionFrame() {
setTitle("Favorite Sports");
setSize (400,200);
setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
JPanel myStuff = makeComponents();
add(myStuff);
setVisible(true);
}
private JPanel makeComponents() {
JPanel myPanel = new JPanel();
messageLabel = new JLabel("Select your favorite sport: ");
rb1 = new JRadioButton(a, true);
rb1 = new JRadioButton(b);
rb1 = new JRadioButton(c);
rb1 = new JRadioButton(d);
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
group.add(rb3);
group.add(rb4);
myPanel.add(rb1);
myPanel.add(rb2);
myPanel.add(rb3);
myPanel.add(rb4);
rb1.addActionListener( new BList() );
rb2.addActionListener( new BList() );
rb3.addActionListener( new BList() );
rb4.addActionListener( new BList() );
myPanel.add(messageLabel);
return myPanel;
}
private class BList implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == rb1){
System.out.println("Your favorite sport is " + a +".");
}
else if(e.getSource() == rb2){
System.out.println("Your favorite sport is " + b +".");
}
else if(e.getSource() == rb3){
System.out.println("Your favorite sport is " + c +".");
}
else if(e.getSource() == rb4){
System.out.println("Your favorite sport is " + d +".");
}
}
}
public static void main(String[] args) {
new ActionFrame();
}
}
【问题讨论】:
标签: java radio-button jpanel