【问题标题】:Removing/Adding JComponents depending on if boolean equals to true or false根据布尔值是否等于 true 或 false 来删除/添加 JComponent
【发布时间】:2013-04-30 17:38:15
【问题描述】:

在我目前正在制作的游戏中,我刚刚创建了一个起始屏幕。该起始屏幕有 4 个JButtons Play、Options、Credit 和 Quit。如果你按下 Play 会出现另一个 JButton,New Game。

我不想这样当你按下新游戏按钮时,开始屏幕消失并且游戏开始(实际游戏和盯着屏幕都延伸JComponent)。

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

在开始屏幕类中,我有一个名为 startGame 的boolean,该布尔值默认等于 false,当您按下新游戏按钮时,它将等于 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();

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

【问题讨论】:

  • 为什么不让所有组件都运行,而是在调用之前隐藏它们的可见性。
  • 你在Timer中的ActionListener,为什么不把它作为startGame按钮的ActionListener呢?
  • @kuporific 因为以后我这样做会更方便
  • @Tdorno 这不会让游戏运行速度变慢吗?
  • @MysticKiller98 我会但你不会注意到它

标签: java swing timer jbutton actionlistener


【解决方案1】:

在您的第二个代码 sn-p 中,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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2022-11-08
    • 1970-01-01
    • 2015-09-06
    相关资源
    最近更新 更多