marius
marius

Reputation: 1

delay doesn`t wotk for java gui(java)

I want to put a delay on a gui. I put 2 for loops, and I repaint a label, but those 2 for loops execute one after one and label is repaint just to the final.

What can I do?

for(int i=0; i<100000; i++){
    System.out.println(i);
}
label.setBackground(Color.RED);
for(int i=0; i<100000; i++){
    System.out.println(i);
}
label.setBackground(Color.green);

Upvotes: 0

Views: 35

Answers (2)

Robo Mop
Robo Mop

Reputation: 3553

You might want to take a look at

docs.oracle.com/javase/7/docs/api/javax/swing/Timer

It's a link to using timers in Java, which helps to remove the for loops from your program.

You can use this instead:

    Timer t = new Timer(2000, YourActionListener);
    t.start();
}//End of method

public void paintComponent()
{
    super.paintComponent(g);
    if(c%2==0)
    {
        label.setBackground(Color.RED);
    }
    else
    {
        label.setBackground(Color.GREEN);
    }
    c++;
}

...

public void actionPerformed(ActionEvent) // How your YourActionListener method looks like
{
    repaint();
}

Upvotes: 2

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

There are several ways to do a delay in a Java program. Simplest option is to do

 Thread.sleep(2000);

Which simply puts the current thread to sleep for 2 seconds. Depending on what you are trying to accomplish though you may need to consider some more complex options.

This option makes your program unresponsive for the sleep time. As you have a (I assume) swing application you can use a Timer instead.

Upvotes: 0

Related Questions