如何从声明的 class 之外的 JFrame 关闭 JFrame

How to close a JFrame from a class outside the one it was declared in

所以我在 Java 中编写游戏贪吃蛇,并在一个 class 中声明我的 JFrame。如您所见,我使用其他 class GamePanelHEIGHTWIDTH)中的一些 class 变量来设置维度以及创建一个实例GamePanel 对于 setContentPane()。我有另一个 class 创建 SnakeGame 的实例,以便实际 运行 游戏。这个 class 将有一个标题画面。 这是 SnakeGame class:

    public final class SnakeGame{
     JFrame frame = new JFrame("SnakeGame");
     GamePanel g = new GamePanel();
     public SnakeGame(){
          //the content of the frame is the g object from the GamePanel class
          frame.setContentPane(g);
          //default close operation is to close when close button is pressed
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          //user can't change size of panel
          frame.setResizable(false);
          frame.pack();

          //size is set
          frame.setPreferredSize(new Dimension(GamePanel.WIDTH, GamePanel.HEIGHT));
          frame.setLocationRelativeTo(null);
          //set visible = true so that the user can see it
          frame.setVisible(true);
     }
}

我希望用户能够按 'esc' 键或按 on-screen 按钮从 GamePanel class 关闭 frame。有什么可行的方法吗?

我尝试在 SnakeGame class 中使用一个方法 return frame,我想我可以从我的 GamePanel class 使用 JFrame 方法来改变 frame,但这似乎不起作用。

这是 GamePanel 的构造函数,如果有帮助的话:

public GamePanel(){
          setPreferredSize(new Dimension(WIDTH, HEIGHT));
          setFocusable(true);
          requestFocus();
          addKeyListener(this);
     }

您可以使用 javax.swing.SwingUtilities 中的 SwingUtilities.getWindowAncestor 函数来获取面板的顶部框架。

这是工作代码:

@Override
public void keyPressed(KeyEvent arg0) {
    if (arg0.getKeyCode() == 27) { // 27 is ascii code for esc button
        JFrame frame = (JFrame)SwingUtilities.getWindowAncestor(this);
        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
    }
}

将此代码放入 GamePanelKeyPressed 函数中。