Search code examples
javaswingshow-hide

Memory game - Make the 2 cards disappear after X time


I wanted to make a "memories" or "find pairs" game for Java, just to start with a basic game before starting something more difficult. My game works very well, but I just have 1 big problem. I don't really know how to hide the 2 images x seconds after the user clicks on the second one.

This is what is done:

  1. The game is created with 4x4 buttons in a array
  2. The values of the cards are distributed (name, position, icon)
  3. The user then clicks on the first card, which shows up immediately
  4. The user clicks on the second one, if the first is equal to the second one then disable the 2, if not then re-hide the 2.

But I don't know how I can make the program show the second card and then after x seconds hide the 2...

How can I solve this?


Solution

  • Depending on what framework you are using, there should be a timer utility available to you.

    For instance, if you are using Swing, then you should be able to use javax.swing.Timer as suggested in the above comments. Follow this link for a simple Swing Timer tutorial. As they say on that page, swing timers can be used in one of two ways and one of those ways is:

    To perform a task once, after a delay

    This sounds like exactly what you are trying to achieve.

    You could also try a library like Joda Time which has lots of features and options.