0

在我目前正在制作的游戏中,我刚刚创建了一个起始屏幕。该起始屏幕有 4JButton秒播放、选项、信用和退出。如果你按下 Play 会出现另一个 JButton,New Game。

我不想这样当您按下新游戏按钮时,开始屏幕消失并且游戏开始(实际游戏和凝视屏幕都扩展JComponent)。

我有一个单独的类来运行游戏并处理游戏中的选项菜单。

在开始屏幕类中,我有一个boolean名为 startGame,该布尔值默认等于 false,当您按下 New Game 按钮时,它将等于 true。在开始菜单类中,我还有一个返回 startGame 值的公共方法,它看起来像这样。

public boolean checkGame(){
    return startGame;
}

在运行游戏的主类中,我使用这样的 Timer 检查 checkGame 方法是否等于 true 或 false。

if(menu.checkGame() == false){
            frame.add(menu);
        }
        Timer timer = new Timer(5, new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(menu.checkGame() == true){
                    frame.remove(menu);
                    frame.add(new Level1());
                }
            }
        });
        timer.start();

显然这是行不通的,因为如果这样我就不会问这个问题了。所以现在我的问题是,我如何让它像我想要的那样工作?

4

1 回答 1

0

在您的第二个代码片段中,Timer仅运行一次其任务。也许你想ScheduledExecutorService反复检查,例如:

    final ScheduledExecutorService scheduledExecutor =
            Executors.newSingleThreadScheduledExecutor();

    scheduledExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (menu.checkGame()) {
                        frame.remove(menu);
                        frame.add(new Level1());
                        scheduledExecutor.shutdown();
                    }
                }
            });
        }
    }, 5, 5, TimeUnit.MILLISECONDS);
于 2013-05-01T14:25:07.770 回答