简体   繁体   中英

Why doesn't setText work for JLabel component?

I have a JLabel which I want to change momentarily, here is the code I have written to do so:

infoLabel.setText("Added");
try {
   TimeUnit.MILLISECONDS.sleep(300);
}
catch(InterruptedException ex)
{
}

infoLabel.setText("Action"); //funny part is when I comment this line it works

My default text for the label is 'Action'

Swing is a single threaded frame work, that means, if you do anything that stops this thread, then it can't respond to any new events, including paint requests.

Basically, TimeUnit.MILLISECONDS.sleep(300) is causing the Event Dispatching Thread to be put to sleep, preventing it from processing any new paint requests (amongst other things).

Instead, you should use a javax.swing.Timer

Take a look at

For more details

For example...

infoLabel.setText("Added");

Timer timer = new Timer(300, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        infoLabel.setText("Action");
    }
});
timer.setRepeats(false);
timer.start();

Note, 300 milliseconds is a really short time, you might like to start with a value a little larger like 2000, which is 2 seconds ;)

You're sleeping the Swing event thread putting the entire GUI to sleep. Don't do that. Use a Swing Timer instead.

您的应用程序在单个线程上运行,因此当您使线程休眠时,可以防止它进行任何GUI更新。

Are you sure you are doing things properly? By doing everything (including sleep) in the GUI thread, it will always be busy and never get back to Java in order to let the GUI be redrawn.

Search for EDT (Event dispatch thread) for more info. Here is one question on the subject: Processing code doesn't work (Threads, draw(), noLoop(), and loop())

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