如何推送选定的选项卡更新(java swing)?
我正在尝试更新正在显示的选项卡,但它似乎要等到方法结束然后更新。有没有办法让正在显示的选项卡立即更新?
这是我遇到此问题的代码示例:
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();
}
});
}
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();
}
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原因是该方法正在事件调度线程中执行,并且任何重绘操作也将发生在该线程中。一种“解决方案”是更新选项卡索引,然后安排剩余的工作稍后在 EDT 上调用;这应该会导致选项卡状态立即更新;例如
编辑
根据下面的评论,如何调用
SwingWorker
以调用runProgram方法的示例如下所示:但是,我在这里感觉到一个更大的问题:事实上,您看到更新选项卡出现明显延迟,这让我认为您正在 EDT 上执行长时间运行的计算。如果是这种情况,您应该考虑在后台线程上执行这项工作。看一下
SwingWorker
类。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. One "solution" is to update the tab index and then schedule the remaining work to be invoked later on the EDT; this should cause the tab state to be updated immediately; e.g.
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: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. If this is the case you should consider performing this work on a background thread. Take a look at the
SwingWorker
class.