Reputation: 1
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
Reputation: 3553
You might want to take a look at
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
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