Search code examples
javaswingconcurrencyevent-dispatch-threadthread-sleep

I want to add a delay in a way, on button click update a label, sleep for few seconds and then update other labels


This is the listener for the button.

 dice.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
           String randomNum = String.valueOf(randomNumber);
           rand.setText(" Move forward "+randomNum+" boxes");  //rand is a label 
           try {
                    Thread.sleep(6000);                 //1000 milliseconds is one second.
               } catch(InterruptedException ex) {
                         Thread.currentThread().interrupt();
               }
           //here some handling with randomNumber
              Position[playerTurn].setText(posi);
     } //end of actionlistener

I want to add sleep between rand.setText and Position[playerTurn].setText but it is not working as expected. It first waits then immediately set both labels which I don't want.


Solution

  • This is because repaint hasn't been called yet. So in the background you are changing the rand text, it waits 6 seconds, then it will set the Position text. But there is no repaint in between, so they will draw at the same time.

        dice.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {     
                String randomNum = String.valueOf(randomNumber);
    
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        try
                        {
                            Thread.sleep(6000);
                        }
                        catch(Exception ie){}
    
                        Position[playerTurn].setText(posi);
                    }
                });
            }
        });
    

    This will start a new Thread, so that will allow the first label to be repainted immediately in your main AWT thread, then you have an offshoot thread here that will fire off in 6 seconds. You will have to determine what you want to do if an exception is caught in the Runnable though.

    EDIT

    Noticed that you are declaring the string inside the listener, which will be an issue for this code. You will need to declare it as final or as an instance variable.