Search code examples
javaswingtime-wait

Make Swing operations immediate


I have a method in Swing to hide and show some buttons, called setScreen(int stage), which will hide or not certain buttons depending on the stage parameter. I want to call the method, then wait a few seconds and then call it again, like in this code:

... //Here stage has been assigned to some value

setScreen(stage);

if (stage != STAGE_TWO) {
  sleep(WAIT_TIME * 1000);
  stage = WELCOME;
  setScreen(stage);
}

The code for setScreen(int stage) is something like this:

void setScreen(int stage) {
    switch (stage) {
        case WELCOME:
            screen.infoLabel.setText("Welcome!");
            screen.startButton.setVisible(true);
            break;

        case STAGE_TWO:
            screen.infoLabel.setText("We are in stage two!");
            screen.startButton.setVisible(false);
            break;
    }

    screen.validate();
}

Where screen is an instantiation of a class extending JFrame.

The problem here is that the first setScreen(stage) is never displayed, since the thread goes to sleep before the changes have been commited. I have tried substituting the sleep for a while loop checking the time of the system, but the effect is the same.

**EDIT: ** I have found in a recommended StackOverflow thread some information on Swing Timer that may be useful. I'll work with it and upload any useful advances I make.


Solution

  • You are sleeping event dispatch thread. Don't do it and use:

    javax.swing.Timer timer = new javax.swing.Timer(WAIT_TIME * 1000, new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            if (stage != STAGE_TWO) {
                stage = WELCOME;
                setScreen(stage);
            }
        }
    });
    timer.start();
    

    The if condition may be for entire timer as per your requirement