2013-05-12 165 views
1

编辑的代码:尝试从另一个类修改JFrame时出现空指针异常?

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

你为什么要使用静态变量?业务的第一阶段:摆脱上面显示的所有静态修饰符。将您的代码带入实例世界。 – 2013-05-12 01:18:43

+0

你已经改变了我的当前答案无关的整个问题。 :(不好, – 2013-05-12 02:06:50

+0

哎呦,我很抱歉,我是这个网站的新手:( – user2373733 2013-05-12 02:11:03

回答

1

您创建的面板类之前创建的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(); 
    } 
    }); 
} 

,并查看可能看起来像:

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; 
    } 
} 
+0

啊,谢谢。现在我很抱歉如果这是一个愚蠢的问题,但我对静态修改器和所有的新东西,因为编译器告诉我(是的,我知道,在知道你在做什么之前,从来没有跟编译器一起)。我怎样才能改变我的程序,所以我的变量不需要是静态的? – user2373733 2013-05-12 01:24:44

+0

@ user2373733:不,编译器没有不会告诉你使用静态修饰符,而是告诉你不能在该上下文中使用静态方法,解决方案不是使用静态方法来创建实例,而是调用不在类上的实例的方法。 ,你需要做的第一件事是摆脱静态修饰符,然后当编译器抱怨,修复问题,而不是使变量静态。 – 2013-05-12 01:25:27

+0

所以你的意思是像frame.add(新的GamePanel())? – user2373733 2013-05-12 01:27:52

相关问题