several times change label text by clicking button in swing not work

好久不见. 提交于 2019-12-02 10:09:23

I would try to use a SwingWorker instance (in particular its doInBackground method) to do what you are currently doing in doWork on a different thread than the main UI thread. The way it's written, your listener method is bound to freeze the user interface during execution, which, as you said, can be a long time, resulting in a bad user experience.

Change to JLabel text can happen in three different places: first, just before invoking execute on (i.e. starting) the SwingWorker; second, using the publish/process mechanism that SwingWorker makes available to publish intermediate results on the user interface; third, in the done method, which is called again on the UI thread as soon as the SwingWorker has finished the execution of its doInBackground method.

References: Oracle's tutorial on worker threads and SwingWorker, JavaDoc API documentation of the SwingWorker class.

Never, NEVER use Thread.sleep, Thead.yield in the ETD

Never, NEVER perform any blocking actions in the ETD, such as extended IO or data processing

The reason that the label is not changing is because you are stalling/blocking the ETD, preventing it from processing any repaint requests.

Check out Concurrency in Swing & The Event Dispatching Thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!