Search code examples
javamultithreadingswingjlabel

How can I cause a JLabel to disappear after a period of time?


I have an issue with my program. I have a button handler that I would like to make a JLabel disappear, then wait one second, then cause a second JLabel to disappear. I thought my code would work, it does a delay, however both JLabels disappear once the method finishes. They disappear at the same time and this isn't what I want. My code is below. Thank you for your help!

private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {                                          

    String numInputStr = inputBox.getText();
    int numInput = Integer.parseInt(numInputStr);

    inputBox.setText("");

    if (numInput == 1) {
        coin1.setVisible(false);
        c1Visible = false;
    } else if (numInput == 2) {
        coin1.setVisible(false);
        c1Visible = false;
        coin2.setVisible(false);
        c2Visible = false;

    } else if (numInput == 3) {
        coin1.setVisible(false);
        c1Visible = false;
        coin2.setVisible(false);
        c2Visible = false;
        coin3.setVisible(false);
        c3Visible = false;
    } else {
        System.err.println("Invalid Input, try again");

    }

    jButton14.setVisible(false);

    try {
        Thread.sleep(1000);
    } catch (Exception E) {

    }

    if ((c1Visible == false) && (c2Visible == true) && (c3Visible == true)) {
        coin2.setVisible(false);
        coin3.setVisible(false);
        coin4.setVisible(false);
    } else if ((c2Visible == false) && (c3Visible == true) && (c1Visible == false)) {
        coin3.setVisible(false);
        coin4.setVisible(false);

    } else if ((c3Visible == false) && (c4Visible == true)) {
        coin4.setVisible(false);
    } else {
        System.out.println("Something went wrong, please try again");
    }


}

Solution

  • I thought my code would work, it does a delay, however both JLabels disappear once the method finishes.

    This is a classic Swing concurrency problem, because you call Thread.sleep() from the EDT which is a single and special thread where Swing event handling takes place and components creation/update should take place too.

    If you block this thread your GUI won't be able to repaint itself and will be freezed until the thread is ready to process Swing related stuff.

    In order to achieve your goal I'd suggest you to use a Swing timer to make those labels disappear after a given period of time.

    For further information about this matter please take a look to: