我正在尝试更新正在显示的选项卡,但它似乎要等到方法结束然后更新。有没有办法让正在显示的选项卡立即更新?
这是我遇到此问题的代码示例:
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();
}
});
}
最佳答案
原因是该方法正在事件调度线程中执行,并且任何重绘操作也会发生在该线程中。一种“解决方案”是更新选项卡索引,然后安排剩余的工作稍后在 EDT 上调用;这应该会导致选项卡状态立即更新;例如
public void actionPerformed(ActionEvent evt) {
tab.setSelectedIndex(1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Do remaining work.
}
});
}
编辑
根据下面的评论,如何调用 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()
但是,我在这里感觉到一个更大的问题:事实上,您在更新选项卡时发现了明显的延迟,这让我认为您正在 EDT 上执行长时间运行的计算。如果是这种情况,您应该考虑在后台线程上执行这项工作。看看SwingWorker
类。
关于java - 如何推送选定的选项卡更新(java swing)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7868806/