我有一个主课:
public class Main extends JFrame {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Main m = new Main();
m.initGUI();
}
});
public void initGUI() {
//add components for this JFrame
//add JPanel with table
//etc..
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
然后我有一个扩展 JPanel 的类:
class CTable extends JPanel {
JTable table;
public void initGUI() {
//add components, table to JPanel etc...
//action listeners to table
}
public void handleTableRowOnClick(String data) {
InfoDialog d = new InfoDialog(data);
//HERE IS MY PROBLEM
//do something else here (THIS SHOULD EXECUTE BUT IT DOESN'T) such as:
String test = "test"
//(IT ONLY EXECUTES AFTER I CLOSE THE DIALOG)
//and I need the ModalityType.APPLICATION_MODAL functionality
}
}
然后我还有另一个类:
class InfoDialog extends JDialog {
JComboBox cb;
String data;
public void initGUI() {
//add components such as JComboBox
//etc...
this.setModalityType(ModalityType.APPLICATION_MODAL);
this.setTitle("test");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public InfoDialog(String data) {
this.data = data;
this.initGUI();
}
}
我的问题是在这种情况下确保 InfoDialog 实例位于同一事件调度线程 (EDT) 中的最佳方法是什么?
感谢您的回复。
最佳答案
最好的解决方案是在创建对话框之前检查EventQueue.isDispatchingThread
...
public void handleTableRowOnClick(final String data) {
Runnable runner = new Runnable() {
public void run() {
InfoDialog d = new InfoDialog(data);
}
}
if (EventQueue.isDispatchingThread()) {
runner.run();
} else {
EventQueue.invokeLater(runner);
}
}
正如我在上一个问题中所说,调用者有责任确保代码正确执行,而不是您的组件。
关于java - 确保在同一 (EDT) 事件调度线程中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16329283/