JLayeredPane 在 getParent() 上返回 null

JLayeredPane returning null on getParent()

我的情况:我有一个扩展 JFrame 的 class MainScreen(它实际上只是一个具有启动应用程序的主要方法的 JFrame),我在其上添加了一个扩展 JLayeredPane 的 class 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 class 向主 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的对象是在调用this.getParent().add(button, BorderLayout.SOUTH);之后添加到MainScreen的。

根据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 的情况下,默认内容窗格是 JPanel。因此,当您调用 this.add(gm, BorderLayout.CENTER); 时,您实际上将 GameManager 的实例添加到 JFrame 的默认内容窗格,即 a JPanel。这就是为什么 GameManager.getParent()JPanel。希望,这会有所帮助。