开发者

Change label text before file read happens

开发者 https://www.devze.com 2023-04-07 00:41 出处:网络
I haven\'t used java in awhile and I am trying to do something like this in one main class: // do stuff

I haven't used java in awhile and I am trying to do something like this in one main class:

// do stuff
this.label.setText("Status: IDLE");
// do things
this.label.setText("Status: LOADING..."); // set to loading right before file read
// read and parse huge file
this.label.setText("Status: DONE");

I want the label to show 'loading...' as the large file read is being executed but the label never freezes (as the job is being ran). How can I force开发者_StackOverflow社区 the label to change during read? Do I need to use separate class/thread? Thanks in advance for your help.


How can I force the label to change during read? Do I need to use separate class/thread?

Yes, you are right. The label and the class that is changing it's value should be in different threads.

Have a look at SwingUtilities invokeLater:

Runnable newThread = new Runnable() {
     public void run() {
     }
 };

You can create a thread this way showed above.


Execute the file IO in a background thread. And you can use SwingUtilities.invokeLater(...) to ensure setting the label text is done in the EDT. Or you can just use the SwingWorker convenience class that does this all for you.

Happy coding.


Use a SwingWorker for the long running task. Then you can publish the text when the label needs to be updated.

Read up on Concurrency in Swing for more background information.


Yes. You need a separate thread. Take a look at JProgressBar and some examples:

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号