编辑代码:
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个面板类中的任何一个修改框架,我得到一个空指针异常,指向我正在修改框架中的某些东西的行。
答案 0 :(得分:1)
在创建JFrame之前,创建了Panel类,因此在Panel类构造函数中JFrame将为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;
}
}