简体   繁体   中英

How to set JLabel text to display before a system sleep

I'm trying to display the text of Successful Login before a system sleep for 3,000 miliseconds. Its not working when I place it right after the set text. How do I get it to display then pause so there is a bit of delay so the user knows that they loging in?

After the user correctly logs-in it will continue to a different class where the JFrame will close

l_Message.setForeground(Color.green);
l_Message.setText("Succesful Login");

try{
    Thread.sleep(3000);
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}

PLOGIN post_login = new PLOGIN();
post_login.postlogin_UI(login_JFrame);

See Concurrency in Swing for the reason why you're having problems

See How to use Swing Timers for a possible solution

import javax.swing.Timer

//...

l_Message.setForeground(Color.green);
l_Message.setText("Succesful Login");
Timer timer = new Timer(3000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        PLOGIN post_login = new PLOGIN();
        post_login.postlogin_UI(login_JFrame);
    }
});
timer.start();

Assuming that you are calling this from outside of the GUI thread(which I believe that you should be), you could try the following:

    EventQueue.invokeLater(() -> {
        l_Message.setForeground(Color.green);
        l_Message.setText("Succesful Login");
    });

    try{
        Thread.sleep(3000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    PLOGIN post_login = new PLOGIN();
    post_login.postlogin_UI(login_JFrame);

ie schedule GUI operations to the GUI thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM