maxpesa
maxpesa

Reputation: 185

Wait for a specified time java (not Thread.sleep( ))

I'm making a simple java game, and I have to make a 3..2..1...Go! My code is like this:

    public void paint321(Graphics g) { // <-- called from paintComponent(Graphics)
    try { 
    int hei = this.getHeight(), wid = this.getWidth();
    g.drawString("3", (int)(wid/2), (int)(hei/2));
    Thread.sleep(1000);
    g.drawString("2", (int)(wid/2), (int)(hei/2));
    Thread.sleep(1000);
    g.drawString("1", (int)(wid/2), (int)(hei/2));
    Thread.sleep(1000);
    g.drawString("Go!", (int)(wid/2)-6, (int)(hei/2));
    }
    catch (InterruptedException ex) { ...

But the game GamePanel (my panel extends JPanel and is on a JFrame) looks white for 3 seconds, and then I see "3","2","1" and "Go!" stucked in each other.

I'm not able to use threads, but I think this is because I tell the computer to don't even show the current thread (my GamePanel, I guess).

My question is: how do I wait a specipied time (1 second in my case) without Thread.sleep()? Or give me an explanation of why I see a white panel

Upvotes: 0

Views: 1351

Answers (3)

babanin
babanin

Reputation: 3584

You should use java.util.Timer (or javax.swing.Timer):

 public void paint321(Graphics g) { 
    int hei = this.getHeight(), wid = this.getWidth();

    java.util.Timer timer = new java.util.Timer();
    timer.schedule(new TimerTask() {
         private int counter = 3;

        @Override
        public void run() {               
            if (counter > 0) {
                g.drawString(String.valueOf(counter), wid / 2, hei / 2);
            } else {
                g.drawString("Via!", wid / 2 - 6, hei / 2);
                timer.cancel();
            }

            counter--;
        }
    }, 0L, 1000L);
}

Upvotes: 2

AlanFoster
AlanFoster

Reputation: 8306

When you use Thread.sleep you are blocking the JFrame/JPanel from updating, as you have blocked that thread.

For a simple solution you can make use of a Java Timer.

If you are using a game loop mechanic however - which you most likely will be using if you are making a game. You can simply keep track of the time you started at and drew the initial number, and if 1 second has elapsed since that time, you draw the next number.

Upvotes: 2

Denis Kulagin
Denis Kulagin

Reputation: 8947

You do sleep in your single GUI thread, which prevents it from properly handling various important events. The only viable solution is to go multithreading.

Upvotes: 0

Related Questions