我有一个 Swing 程序,它根据一些文本字段的内容和一对单选按钮(在按钮组中)的设置进行搜索。当某些文本字段失去焦点时,程序将自动搜索。当单击其中一个单选按钮触发失去焦点事件时,问题就出现了。在单选按钮 isSelected() 值更改之前处理文本字段上的丢失焦点事件,因此使用“错误”(即旧)参数完成搜索,而不是基于单选的新设置的参数纽扣。
我尝试使用我自己的 invokeWhenIdle 方法(如下所示)调用搜索以在事件队列稳定后运行搜索,但它仍然使用单选按钮的旧设置。
我唯一可行的解决方案是在失去焦点事件中延迟 250 毫秒,然后再运行搜索,以便单选按钮有时间更改。这行得通,但它使 UI 看起来很迟钝。
有更好的想法吗?
public static void invokeWhenIdle(final int a_max_retry, final Runnable a_runnable) {
if (a_max_retry <= 0) {
throw new IllegalStateException("invokeWhenIdle: Could not run " + a_runnable);
}
// get the next event on the queue
EventQueue l_queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
AWTEvent l_evt = l_queue.peekEvent();
if (l_evt == null) {
// nothing left on the queue (but us), we can do it
SwingUtilities.invokeLater(a_runnable);
} else {
// still something in the queue, try again
SwingUtilities.invokeLater(new Runnable() {
public void run() {
invokeWhenIdle(a_max_retry - 1, a_runnable);
}
});
}
}