简体   繁体   English

如何让JButton等待一秒钟?

[英]How to make JButton wait One Second?

OK So I am making a Game Called "Connect Four". OK,所以我正在制作一个名为“ Connect Four”的游戏。 What I am Trying do is something like this. 我正在尝试做的是这样的事情。 So once you press the Button called "Human vs Computer" it should says "Your Game Starts in" "3" (now it should wait One second then it should print) "2" (now it should wait One second then it should print) "1". 因此,一旦按下名为“ Human vs Computer”的按钮,它应该显示“您的游戏开始于”“ 3”(现在应该等待一秒钟然后应该打印)“ 2”(现在应该等待一秒钟然后应该打印) )“ 1”。

But when I do it.. it would freeze the "Human Vs Computer Button" which I Don't know why Does it do it. 但是,当我这样做时,它会冻结“人与计算机按钮”,我不知道为什么这样做。 So can you tell me how to fix that issue. 因此,您能告诉我如何解决该问题。 This is what I have tried so far. 到目前为止,这是我尝试过的。

private class humanVsComputerButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {      

  if (event.getSource() == humanVsCom) {

    lblWelcome.setVisible(true);
    playButton.setVisible(false);
    ruleButton.setVisible(true); 
    quitButton.setVisible(true);
    humanVsCom.setVisible(false);
    multiplayer.setVisible(false);
    withTimeLimit.setVisible(false);
    noTimeLimit.setVisible(false);
    ruleButton.setVisible(false);
    quitButton.setVisible(false);
    goBack.setVisible(false);          
    lblGameStarts.setVisible(true);

    try {
      Thread.sleep(5000);                        
    }catch (Exception e) {
    }

    lblGameStarts.setVisible(false);          
    lblinThree.setVisible(true); 

    try {
      Thread.sleep(5000);                        
    }catch (Exception e) {
    }

    lblinThree.setVisible(false);
    lblinTwo.setVisible(true);

    try {
      Thread.sleep(5000);                        
    }catch (Exception e) {
    }

    lblinTwo.setVisible(false);
    lblinOne.setVisible(true);

    try {
      Thread.sleep(5000);                        
    }catch (Exception e) {
    }

    lblinOne.setVisible(false);          
  }
}
}  
}

after some Seconds it would Print everything in just one Line. 几秒钟后,它将只打印一行。

在此处输入图片说明

Please help me fix this issue. 请帮助我解决此问题。 Thank You. 谢谢。

This whole program runs one one thread (unless you create or the program creates any threads). 整个程序运行一个线程(除非您创建或程序创建任何线程)。 So to run something separately on its own thread you do something like the following: 因此,要在自己的线程上单独运行某些内容,您需要执行以下操作:

if (event.getSource() == b) {
Thread th=new Thread() {
  public void run() {
    b.setText("1");
    try {
      Thread.sleep(5000);                        
    }catch (Exception e) {
    }
    b.setText("2");
    try {
      Thread.sleep(5000);                        
    }catch (Exception e) {
    }
    b.setText("3");   
  }
};
th.start();
}

Inside the run() method you put what you want to execute. 在run()方法中,放入要执行的内容。

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

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