0

This a code written using java to delay the execution of the code by 5 seconds. But it is not working. either "this.jLabel2.setText("TDK");" statement not working. Can any one please help me to solve this problem.

 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    this.jLabel2.setText("TDK");
    boolean result=false;
    result=stop();
    if(result)
    {
      this.jLabel1.setText("MDK");
    }
}
public boolean stop()
{
    String current= new java.text.SimpleDateFormat("hh:mm"
            + ":ss").format(new java.util.Date(System.currentTimeMillis()));
    String future=new java.text.SimpleDateFormat("hh:mm"
            + ":ss").format(new java.util.Date(System.currentTimeMillis()+5000));   

    while(!(current.equals(future)))
    {
       current= new java.text.SimpleDateFormat("hh:mm"
               + ":ss").format(new java.util.Date(System.currentTimeMillis()));  
    }

      return true;
}
tdk
  • 29
  • 3
  • possible duplicate of http://stackoverflow.com/questions/3342651/how-can-i-delay-a-java-program-for-a-few-seconds – Dennis Meng Aug 28 '13 at 18:46
  • Ever heard of the "sleep" function? Doing a while loop like that is going to eat up CPU cycles. Also, the loop may not run fast enough for current time to actually equal future, you'll have to see if current time is >= future. – PherricOxide Aug 28 '13 at 18:46
  • note: you do not want to delay in the EDT..you'll freeze the UI. – mre Aug 28 '13 at 18:46
  • I guess your code is working and you should see "MDK" after 5 seconds of freeze. Also [Spinlocks](http://en.wikipedia.org/wiki/Spinlock) ftw. – zapl Aug 28 '13 at 19:03
  • @zapl Yes MDK is showing after 5 seconds. But "TDK" is not showing when i pressed the button. "TDK" is also showing after 5 seconds – tdk Aug 28 '13 at 19:11
  • That's because you are blocking the thread that's responsible for the drawing. Take a look at the answers. – kiheru Aug 28 '13 at 19:13

2 Answers2

3

You are blocking the event dispatch thread (no, don't use Thread.sleep() either). Use a swing Timer:

Timer timer = new Timer(HIGHLIGHT_TIME, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        jLabel1.setText("MDK");
    }
});
timer.setRepeats(false);
timer.start();

where HIGHLIGHT_TIME is the time you want to delay setting the text.

kiheru
  • 6,588
  • 25
  • 31
1

Use the javax.swing.Timer with setRepeats set to false.

mre
  • 43,520
  • 33
  • 120
  • 170