2013-05-12 81 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

相關問題