簡體   English   中英

嘗試從另一個類修改JFrame時出現空指針異常?

[英]Null pointer exception while trying to modify a JFrame from another class?

編輯代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM