java - Swing 在作业运行时更新 UI 组件

标签 java multithreading swing swingworker

我正在开发 Swing 应用程序。因为我有一个工作流程要完成。

我在 for 循环中一个接一个地运行这些作业。有趣的是我必须使用当前正在运行的作业名称更新 GUI 状态栏。

我不能使用 SwingUtilities.invokeAndWait,因为它不能在将成为当前运行线程的调度线程上运行。

我尝试使用 SwingWorker,因为作业在循环中运行,SwingWorker 的 doBackGrount() 方法将执行并返回并获取下一个索引以运行下一个作业。在 SwingWorker 的 done() 中,我编写了代码以使用状态更新 GUI。

public class TestAction extends SwingWorker<Boolean, Void> {

    boolean executeThread = false;

    public TestAction() {
    }

    @Override
    protected Boolean doInBackground() throws Exception {
        executeThread = ExecuteWebServiceAction.webServiceExecution();
        return executeThread;
    }

    @Override
    protected void done() {
        try {
            boolean isOver = (boolean) get();
            if (isOver) {
                MainApplication.getInstance().getFrame().setStatus(LangUtil.getString("cdsExecuteFinehed")
                        + " " + ((WebServiceTool) DrawingManager.getInstance().getCurrentTool()).getName());
                FrameMain.jPanel6.repaint();
            }
        } catch (Interr`enter code here`uptedException ex) {
            Logger.getLogger(TestAction.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExecutionException ex) {
            Logger.getLogger(TestAction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

这就是调用 TestAction 的地方:

if (!WorkFlow.isIsWorkflow()) {
    SwingUtilities.invokeLater(
      new Runnable() {
        @Override
        public void run() {
          webServiceExecution();
        }
    });
} else {
     new TestAction().execute();
}

最佳答案

running in a loop one after the other and notify UI when one is done

听起来像是“大工程,中间结果”。通过发布/处理方法支持中间结果:

  • 实现 doInBackground 以循环遍历作业并在作业终止时调用发布
  • 执行 ui 更新的流程

关于java - Swing 在作业运行时更新 UI 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9698884/

相关文章:

java - 调用事件调度线程

java - 在Java中调用类中的方法

Java泛型编程: Determining if class extends another

java - SpringBoot 获取应用程序的 @RestController 列表,即 List<@RestController>

Java EE 教程示例因以下错误而失败

Java JSF h :outPutText - no tag was defined

c++ - 将参数从主线程传递到线程。当线程退出时,主线程重置为0。为什么?

使用中的 Java 泛型类

database - 在ring网站中使用atom作为内存数据库

java - 在 Swing 中创建用于表单输入的 Java GUI