I am making a matching game in java and it is going pretty well. The problem is that when I click on a second card, if they are not the same the cards turn back, but it never shows you what the second card is. I was thinking about delaying the program after the two cards are shown, but it won’t work. It only shows the first card, delays the program and then does what it did in the first place. It won’t show the second picture. I’ve tried wait() and Thread.sleep(1000), but none of them will produce the effect I want.
// code above where it finds the first card and shows it
y.setIcon(FindTheCard(es2,'c')); //showing the second card
try{Thread.sleep(3000L); // delaying
}catch(Exception e){}
I am pretty new to threads, so I guess the first thing that runs is the thread and then the rest of the code, which is not what I want. I want y.setIcon(..) to be executed and then to have a little delay before the rest of the code runs.
Everything about my code works perfectly, so I suppose it’s just my lack of knowledge. All I need is the delay.
However, I have also tried this code:
public class testing {
public static void main(String[] args) {
System.out.println("Do this stuff");
try { Thread.sleep(500); }
catch ( Exception e ) { }
System.out.println("Now do everything after this");
}
}
and it works. There is a little delay between the two sentences. How can I do the same with my cards – which are actually buttons. I also removed the code where it turns the cards back after they’re shown and the cards do stay the same. So there’s no problem regarding the second card or the icon.
As mentioned, Swing is single threaded. There is a single thread, called the Event Dispatch Thread that performs all rendering and is where all Swing events are handled (your
ActionListenersand other sorts of listeners all run on that thread). It is important not to perform any long running processes (server calls, disk I/O, Thread.wait()s) on that thread, because it will cause the GUI to hang. Look at this tutorial for more detail and examples.For your case, you may also want to look at Swing Timers, as they seem purpose built for your desired effect.