简体   繁体   English

从另一个线程更新JLabel,而不必在线程上分离所有进程?

[英]Update a JLabel from another thread without having to separate all my processes on threads?

I'm developing a big project on Java Swing. 我正在开发有关Java Swing的大型项目。 It has a database connection, external devices managing and sd-cards processing. 它具有数据库连接,外部设备管理和SD卡处理功能。

I currently have a lot of heavy processes that run on the EDT thread, and making separated threads for all of them is a long long task that I'm trying to escape... Besides, It would probably introduce a lot of concurrency problems that I am not willing to handle. 我目前在EDT线程上运行着很多繁重的进程,因此为它们创建单独的线程是一个漫长的任务,我正试图逃避……此外,它可能会引入很多并发问题,我不愿意处理。

The thing is that I want to introduce a loading JLabel with a loading gif while the long busy tasks are being processed. 事实是,在处理长时间繁忙的任务时,我想引入带有加载gif的加载JLabel It is also important to highlight that I want my whole swing interface to be blocked while the long tasks are being done, just like it happens now, EXCEPT for the loading label. 同样重要的是,要突出显示我希望在完成长任务时阻止整个挥杆界面,就像现在发生的那样,除了加载标签。

Is there a way to actualize that label from another thread? 有没有办法从另一个线程实现该标签?

If you care about creating a good user experience, there really is no escaping using SwingWorker or similar, to offload work form the event dispatcher thread (EDT). 如果您希望创建良好的用户体验,那么实际上并没有使用SwingWorker或类似工具来逃避事件分配器线程(EDT)的工作。 If you need to really need to "block" the UI, you should use a JDialog with a progress bar or similar. 如果确实需要“阻止” UI,则应使用带有进度条或类似控件的JDialog。

The short answer to your question is no. 您问题的简短答案是“否”。 The Jlabel must be instantiated and added from the EDT. Jlabel必须实例化并从EDT添加。

However, you should be able to add the JLabel, you just have to make sure you do it before the long-running blocking tasks starts. 但是,您应该能够添加JLabel,只需确保在长时间运行的阻塞任务开始之前就已添加了JLabel。 Then remove it after it is done. 完成后将其删除。

Anyway, this is a hack, and a lazy workaround for doing the right thing, and is not recommended. 无论如何,这是一个hack,是一种做正确事情的懒惰解决方法,因此不建议这样做。 You might experience that you spend more time working around the issue and pulling your hair, than just do it properly with SwingWorkers. 您可能会发现,与仅使用SwingWorkers进行正确处理相比,您花费更多的时间来解决问题并拔头发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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