Search code examples
javathread-sleep

using sleep method in gui, not working


public void actionPerformed( ActionEvent evt)  
{
  if( combo1==true && !evt.getActionCommand().equals("correct"))
  {
    combo2 = true;
    combo1 = false;
    combo3 = false;
    outText.setText("One more try!");
  }
  else if( combo2==true && !evt.getActionCommand().equals("correct"))
  {
    combo1 = false;
    combo2 = false;
    combo3 = true;

    **outText.setText("Wrong!!");**

      //sleep for 1 second
    try {
            Thread.currentThread();
          Thread.sleep(1000);
         } 
    catch (Exception ex) 
    {
    System.exit(0);
    }

    System.exit(0);
  }
  else if( !evt.getActionCommand().equals("correct"))
  {
    combo1=true;
    combo2=false;
    combo3=false;
    outText.setText("Two more tries!");
  }
  else
    outText.setText("Correct");
}

This is a part of my code for getting the right answer, but the line where it's marked with ** is not working with the sleep method in there. The program sleeps for a sec and closes, but wouldn't print out "Wrong!!" before it goes into sleep. If someone could help me that'd be much appreciated! Thanks in advance.


Solution

  • You're blocking the method from completing execution with Thread.sleep(). Use a javax.swing.Timer` instead.

    outText.setText("Wrong!!");
    new javax.swing.Timer(1000, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }).start();
    
    // get rid of Thread.sleep()
    

    See more at How to Use Swing Timers