gpt4 book ai didi

java - 单选按钮无法正确显示

转载 作者:行者123 更新时间:2023-11-29 05:29:37 24 4
gpt4 key购买 nike

我只是在学习单选按钮,我以为我终于明白了,因为它编译得很好。但是当我尝试运行该程序时,出现了这个错误:

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

最佳答案

您已将所有单选按钮命名为 rb1,因此其他组件永远不会被初始化

rb1 = new JRadioButton(a, true);
rb2 = new JRadioButton(b);
rb3 = new JRadioButton(c);
rb4 = new JRadioButton(d);

关于java - 单选按钮无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21567177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com