我的情况:我有一个扩展 JFrame 的 MainScreen 类(它实际上只是一个具有启动应用程序的 main 方法的 JFrame),我在其中添加了一个扩展 JLayeredPane 的类 GameManager,我用它来显示某些内容。
public static void main(String[] args) {
MainScreen ms = new MainScreen();
}
public MainScreen() {
this.initScreen();
this.gm = new GameManager();
this.add(gm, BorderLayout.CENTER);
this.setVisible(true);
}
现在,我想要做的是,从 GameManager 类中,我想向主 JFrame 添加一个 JButton。我认为这很容易,只需这样做:
JButton button = new JButton("Hello");
this.getParent().add(button, BorderLayout.SOUTH);
但是 getParent() 返回 null,所以显然它不起作用。但我不知道为什么,我之前做了类似的事情(尽管使用了 JComponent 和 JPanel),并且我认为添加到容器中的每个 JComponent 都会将该容器作为其父级。我错过了什么?
最佳答案
如果有如下语句:
this.getParent().add(button, BorderLayout.SOUTH);
存在于 GameManager.java
的构造函数中,然后getParent() is returning null
是正确的。是因为GameManager
的对象添加到MainScreen
调用 this.getParent().add(button, BorderLayout.SOUTH);
后。
根据 https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html
Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI.
如果是JFrame
默认内容 Pane 是 JPanel
。因此,当您调用this.add(gm, BorderLayout.CENTER);
时,您实际上添加了 GameManager
的实例到默认内容 Pane JFrame
即a JPanel
。这就是为什么GameManager.getParent()
是 JPanel
。希望这会有所帮助。
关于java - JLayeredPane 在 getParent() 上返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38041100/