[英]How can I push a selected tab update (java swing)?
I'm trying to update the tab being displayed, however it seems to wait until the end of the method and then update. 我正在尝试更新所显示的选项卡,但是它似乎要等到方法结束后再进行更新。 Is there a way to make the tab being displayed update immediately? 有没有一种方法可以使显示的选项卡立即更新?
Here is an example of the code where I'm having this issue: 这是我遇到此问题的代码示例:
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();
}
});
}
The reason for this is that the method is being executed in the Event Dispatch thread, and any repaint operations will also occur in this thread . 这样做的原因是该方法正在Event Dispatch线程中执行,并且任何重新绘制操作也将在此线程中发生 。 One "solution" is to update the tab index and then schedule the remaining work to be invoked later on the EDT; 一种“解决方案”是更新选项卡索引,然后安排其余工作在以后的EDT上调用; this should cause the tab state to be updated immediately; 这将导致选项卡状态立即更新; eg 例如
public void actionPerformed(ActionEvent evt) {
tab.setSelectedIndex(1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Do remaining work.
}
});
}
EDIT 编辑
Per your comment below an example of how to invoke a SwingWorker
in order to call your runProgram method would look something like this: 在下面的评论中,有关如何调用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()
However, I sense a bigger problem here: The fact that you are seeing a significant delay in updating the tab makes me think you are performing long running calculations on the EDT. 但是,我在这里感觉到一个更大的问题:事实上,您看到更新选项卡的时间显着延迟,这让我认为您正在EDT上进行长时间的计算。 If this is the case you should consider performing this work on a background thread. 如果是这种情况,则应考虑在后台线程上执行此工作。 Take a look at the SwingWorker
class. 看一下SwingWorker
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.