Confused Boo
Confused Boo

Reputation: 1

How do you delay in the middle of an action preformed?

I'm trying to create a card match game. When the user clicks a card button I want it to set a random picture, then the user clicks another card button; I want it to pause the code to show the image for a split second and then check if the two are the same, match them, or if not set the cards back. However since it sets the cards back, the user doesn't get to see what's behind the second card. When trying to get the pause within the action, it pauses the whole action and then performs everything within it. I want it to just pause in between as shown below. Please help would be appreciated!

I've tried to change the positioning of where the thread.sleep is but nothing fixes it. The guess() method checks to see if the cards match and then flips them accordingly.

private void card1ButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
       String temp = cards.get(0);

       if (temp.equals("0")) {
           card1Button.setIcon(a);
       } else if (temp.equals("1")) {
           card1Button.setIcon(b);
       } else if (temp.equals("2")) {
           card1Button.setIcon(c);
       } else if (temp.equals("3")) {
           card1Button.setIcon(d);
       } else if (temp.equals("4")) {
           card1Button.setIcon(e);
       } else if (temp.equals("5")) {
           card1Button.setIcon(f);
       } else if (temp.equals("6")) {
           card1Button.setIcon(g);
       } else if (temp.equals("7")) {
           card1Button.setIcon(h);
       }

       // I want to pause here, but it pauses before any code in this event is executed, and then it executes
       try {
           Thread.sleep(1000);
       } catch (InterruptedException ex) {
           Logger.getLogger(MemoryUI.class.getName()).log(Level.SEVERE, null, ex);
       }

       count++;
       if (count == 1) {
           c1 = Integer.parseInt(temp);
           change[0] = 0;
       } else if (count == 2) {
           c2 = Integer.parseInt(temp);
           change[0] = 0;
           guess();

       }
   }```

Upvotes: 0

Views: 37

Answers (1)

WJS
WJS

Reputation: 40034

You don't. If you delay in any method that operates on the EDT (Event Dispatch Thread) you will lock up all other events including painting for that time period. So set a flag in the actionPerformed method and then use that to do your delay. Or consider incorporating the Timer class (javax.swing.Timer or java.util.Timer as appropriate) into your application

In general, all processing within the EDT should be kept to a minimum. And painting and anything that responds to events via some listener all run on the EDT.

Upvotes: 2

Related Questions