Search code examples
javadelay

Setting a delay in a java program


I'm sorry for such a newbie question, I'm trying to set a delay between two JText fields changing color i.e:

 box1.setBackground(Color.yellow);
 box2.setBackground(Color.red);

I've tried to use:

try {
    Thread.sleep(1000); 
}catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}

However when using this, the delay happens instantly and both colors only change after the delay. Thank you in advance for any light you shine on my situation :)


Solution

  • box1.setBackground(Color.yellow);
    new Thread(new Runnable(){
       public void run(){
           try{
              Thread.sleep(1000);
           }catch(InterruptedException ex){
              ex.printStackTrace();
           }
           box2.setBackground(Color.red);
       }
    }).start();
    

    If you execute Thread.sleep(1000); on main thread, the rendering of the page will be done once sleep is terminated and you will see both box changing their color.

    If sleep runs in another thread different from main thread, mainThread rendering will be done immediately after the new thread is started and you can see the first box chaning his color. After the sleep is executed, box2 will change his color. Sorry for my english, i hope you can understand it :)