如何推送选定的标签更新(java swing)?

The*_*imp 0 java swing tabs updatepanel

我正在尝试更新正在显示的选项卡,但它似乎要等到方法结束然后更新.有没有办法让标签显示立即更新?

以下是我遇到此问题的代码示例:

private static void someButtonMethod() 
{
    Button = new JButton("My Button");
    Button(new ActionListener() {
        public void actionPerformed(ActionEvent e) 
        {
            tabs.setSelectedIndex(1);

            // Do some other things (In my case run a program that takes several seconds to run).
            runProgram();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*ski 6

原因是该方法正在Event Dispatch线程中执行,并且任何重绘操作也将在此线程中发生.一个"解决方案"是更新选项卡索引,然后安排稍后在EDT上调用的剩余工作; 这应该导致选项卡状态立即更新; 例如

public void actionPerformed(ActionEvent evt) {
  tab.setSelectedIndex(1);

  SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      // Do remaining work.
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

编辑

根据下面的评论,如何调用a SwingWorker以调用runProgram方法的示例如下所示:

// Typed using Void because runProgram() has no return value.
new SwingWorker<Void, Void>() {
  protectedVoid doInBackground() {
    runProgram();
    return null; // runProgram() doesn't return anything so return null.
  }

  protected void done() {
    // Called on the EDT when the background computation has completed.
    // Could insert code to update UI here.
  }  
}.execute()
Run Code Online (Sandbox Code Playgroud)

但是,我在这里感觉到一个更大的问题:你看到更新标签时出现明显延迟这一事实让我觉得你在EDT上执行长时间运行的计算.如果是这种情况,您应该考虑在后台线程上执行此工作.看看SwingWorker课程.