[英]Null pointer exception while trying to modify a JFrame from another class?
EDITED CODE: 编辑代码:
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);
}
No matter what outside class I try to modify the frame from (any of the 3 panel classes above), I get a null pointer exception pointing to the line I am modifying something in the frame. 无论我尝试从哪个外部类修改框架(上面的3个面板类中的任何一个),我都会得到一个空指针异常,该异常指向我正在修改框架中某些内容的行。
Your Panel classes are created before the JFrame is created so the JFrame will be null in the Panel class constructors. 您的Panel类是在创建JFrame 之前创建的,因此JFrame在Panel类构造函数中将为null。 But as per my comment, you should bring your code into the instance world by getting rid of those static modifiers.
但是根据我的评论,您应该摆脱那些静态修饰符,将代码带入实例世界。 Your whole program design, to put it mildly, smells.
总体来说,整个程序设计都有气味。 Your main method should instead look something like:
您的主要方法应改为:
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();
}
});
}
And View could look like: 而且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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.