简体   繁体   English

根据布尔值是true还是false来删除/添加JComponent

[英]Removing/Adding JComponents depending on if boolean equals to true or false

In a game that I am currently making I have just created a starting screen. 在我当前正在制作的游戏中,我刚刚创建了一个开始屏幕。 That starting screen have 4 JButton s Play, Options, Credit and Quit. 该开始屏幕有4个JButton的Play,Options,Credit和Quit。 If you press Play another JButton will appear, New Game. 如果按“播放”,则会出现另一个JButton,即“新游戏”。

I wan't to make it so that when you press the New Game button the starting screen disapears and the game start (both the acctual game and the staring screen extends JComponent ). 我不想这样做,所以当您按“新建游戏”按钮时,开始屏幕消失并且游戏开始(虚拟游戏和凝视屏幕都扩展了JComponent )。

I have a seperate class that runs the game and handels the in-game option menu. 我有一个单独的类来运行游戏并处理游戏中的选项菜单。

In the starting screen class I have a boolean called startGame, that boolean equals to false by default and when you press the New Game button it will equal to true. 在开始屏幕类我有一个boolean称为startGame,那布尔默认等于假,当你按下新游戏按钮,它会等于true。 In the starting menu class I also have a public method that returns the value of startGame, it looks like this. 在开始菜单类中,我还具有一个公共方法,该方法返回startGame的值,如下所示。

public boolean checkGame(){
    return startGame;
}

In the main class that runs the game I check if the checkGame method equals to true or false by using a Timer like this. 在运行游戏的主类中,我通过使用此类计时器来检查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();

Obviously this does not work because if it would I would not be asking this question. 显然这是行不通的,因为如果可以的话,我不会问这个问题。 So now to my question, how would I make it work like I want? 所以现在我的问题是,我如何使它像我想要的那样工作?

In your second code snippet, the Timer only runs its task once. 在第二个代码段中, Timer仅运行一次任务。 Perhaps you want a ScheduledExecutorService to repeatedly check, for example: 也许您希望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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM