gpt4 book ai didi

java - 尝试从另一个类修改 JFrame 时出现空指针异常?

转载 作者:太空宇宙 更新时间:2023-11-04 07:38:01 25 4
gpt4 key购买 nike

编辑代码:

public static void main(String[] args){

JFrame frame = new JFrame();

frame.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(new StartPanel());
frame.add(new InstructionsPanel());
frame.add(new GamePanel());

frame.getContentPane().getComponent(1).setVisible(false);
frame.getContentPane().getComponent(2).setVisible(false);

frame.setPreferredSize(new Dimension(500, 500));
frame.pack();
frame.setVisible(true);

}

无论我尝试从哪个外部类(上面的 3 个面板类中的任何一个)修改框架,我都会收到一个空指针异常,指向我正在修改框架中的某些内容的行。

最佳答案

您的 Panel 类是在创建 JFrame 之前创建的,因此 JFrame 在 Panel 类构造函数中将为 null。但根据我的评论,您应该通过摆脱这些静态修饰符将代码带入实例世界。温和地说,你的整个程序设计有味道。您的主要方法应该类似于:

private static void createAndShowGui() {
// Model model = new MyModel();
View view = new View();
// Control control = new MyControl(model, view);

JFrame frame = new JFrame("My GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(view.getMainComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}

View 可能看起来像:

public class View
private StartPanel s = new StartPanel();
private InstructionsPanel i = new InstructionsPanel();
private GamePanel g = new GamePanel();
private JPanel mainComponent = new JPanel();

public View() {
// create your GUI here
// add components to mainComponent...
}

public JComponent getMainComponent() {
return mainComponent;
}
}

关于java - 尝试从另一个类修改 JFrame 时出现空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16503272/

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