关闭父级中的 JFrame Class

Closing a JFrame in Parent Class

我正要编写一个小游戏。我有我的主要 class MenuFrame,我从中调用我的 Gui class 来绘制我的游戏。

MenuFrame.java:

public class MenuFrame extends JFrame implements ActionListener {

    private JButton start;

    public static void main(String[] args) {
        MenuFrame mainframe = new MenuFrame("Menu");
        mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainframe.setSize(600, 400);        
        mainframe.setLayout(null);
        mainframe.setVisible(true);
    }

    public MenuFrame(String title) {        
        super(title);           
        start = new JButton("Start game");
        start.setBounds(220, 60, 160, 40);
        start.addActionListener(this);
        add(start);
    }

    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == start) {
            game(hauptSpiel);
        }
    }

    public static void game() {
        JFrame game = new JFrame;
        game.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        game.setUndecorated(true);
        game.setResizable(false);
        game.setSize(480, 800);
        game.setLocation(1920/2-480/2, 1080/2-800/2);
        game.setVisible(true);
        game.add(new Gui());        
    }
}

如你所见,我从我的 void game().
中调用了我的 class Gui() 在我的 Gui class 里,我画了一些画。

class 看起来有点像这样:

public class Gui extends JPanel implements ActionListener {

    public Gui() {              
        setFocusable(true); 
        ImageIcon i = new ImageIcon(background.jpg);
        background = i.getImage();

        ImageIcon b = new ImageIcon("ball.png");
        ball = b.getImage();
    }   

    public void paint(Graphics g) {
        Graphics2D f2 = (Graphics2D)g;

        f2.drawImage(background, 0, 0, null);
        f2.drawImage(ball, 0, 600, null);
    }   
}

为了清晰易懂,我删除了我的游戏逻辑。

不过,如果游戏结束了,我想把我的game()JFrame放在MenuFrameClass里。

有什么办法可以做到干净利落吗?

我可以想到两种方法来做到这一点。我自己在这方面还很陌生,但我自己 运行 遇到过几次这种情况。这是我的做法(我个人喜欢选项 2,但不知道这是否是公认的 OOP 技术)

自上而下:垃圾收集 MO

1) 在 MenuFrame 中有一个定期调用的方法,并检查 GUI/game 对象中的布尔值,指示对象是否已完成。如果属实,请处理掉它。

自下而上:主动的儿童 MO

2) 在 MenuFrame 中有一个方法可以处理作为参数发送给它的对象。从 "game" 中调用所述方法,将其自身作为参数传递。该方法可以是静态的以清除实例问题。如果安全是一个问题(不希望处理随机对象)指定如果调用所述方法,则处理 Child "game"。有点像 getter/setter 方法,它限制了确切可以处理的可能性。

也请分享您的想法。