How do I invoke an immediate update to a Java GUI? (conflict with Thread.sleep())

后端 未结 1 851
面向向阳花
面向向阳花 2021-01-18 05:48

I am making the game Memory, when you pick two cards and if they match you get to keep them, otherwise you turn them back. If you then remember cards you have already chosen

相关标签:
1条回答
  • 2021-01-18 06:36

    Don't call Thread.sleep(...) on the main Swing thread, the EDT. Ever. Instead use a Swing Timer.

    Consider using JLabels to display your images, and then you could "flip" your cards by simply swapping out ImageIcons. When the second card has been flipped, if there's no match, start a non-repeating Swing Timer with a delay for xxxx ms, and in the Timer's ActionListener's actionCommand method have it revert both JLabel's back to the default ImageIcon.

    The javax.swing.Timer tutorial can be found here: How to use Swing Timers

    Edit:
    Regarding your comment about using g.drawString: it's even easier now since all you have to do is swap out your JLabel's text. But later if you decide to upgrade the program to display images, you've got it all set to do this.

    Edit 2:
    Regarding your question about making a new ActionListener class: I'd use an anonymous inner class for this. For example:

      int delayTime = 2 * 1000;
      javax.swing.Timer myTimer = new Timer(delayTime, new ActionListener() {
    
         @Override
         public void actionPerformed(ActionEvent e) {
            // TODO: put in the code you want called in xxx mSecs.
         }
      });
      myTimer.setRepeats(false);
      myTimer.start();
    
    0 讨论(0)
提交回复
热议问题