多次通过点击挥动按钮更改标签文本无法正常工作 [英] several times change label text by clicking button in swing not work

查看:81
本文介绍了多次通过点击挥动按钮更改标签文本无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过一次点击按钮更改jlabel.text几次。在这段代码中,我需要设置标签文本在dowork()函数之前启动并在中间设置为正在进行中并在dowork()之后将其设置为结束(jlabel和dowork中的状态类型长时间执行):

I need to change jlabel.text several times by one click button in swing. In this code i need set label text to start before dowork() function and set to in progress in middle and set it to end after dowork() (status type in jlabel and dowork has long time execution) :

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
        status.setText("start");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            Logger.getLogger(PelakInRFID.class.getName()).log(Level.SEVERE, null, ex);
        }
        status.setText("in progress");
        dowork();
       try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            Logger.getLogger(PelakInRFID.class.getName()).log(Level.SEVERE, null, ex);
        }
        status.setText("end");

 }

在此代码状态中,仅设置为结束并开始运行显示。

In this code status only set to end and start doesn't show.

推荐答案

我会尝试使用 SwingWorker 实例(尤其是 doInBackground 方法)在与主UI线程不同的线程上执行您当前在 doWork 中执行的操作。它的编写方式,你的监听方法必然会在执行期间冻结用户界面,正如你所说,这可能需要很长时间,导致糟糕的用户体验。

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.

更改为 JLabel 文本可以在三个不同的地方发生:首先,在调用执行之前(即启动) SwingWorker ;第二,使用发布 / 进程机制 SwingWorker make可用于在用户界面上发布中间结果;第三,在完成方法中,只要 SwingWorker 完成执行,就会在UI线程上再次调用该方法其 doInBackground 方法。

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.

参考文献:Oracle关于工作线程和 SwingWorker ,JavaDoc API SwingWorker 类的文档

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

这篇关于多次通过点击挥动按钮更改标签文本无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆