[英]Make sure in same (EDT) event dispatching thread
I have a main class: 我有一个主要课程:
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);
}
} }
then I have a class which extends JPanel: 然后我有一个扩展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
}
}
then I have another class: 那我还有另一堂课:
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();
}
}
My question is what is the best method in this situation to make sure InfoDialog instance is in the same event dispatching thread (EDT)? 我的问题是,在这种情况下,确保InfoDialog实例位于同一事件调度线程(EDT)中的最佳方法是什么?
Thank you for any responses. 感谢您的回复。
The best solution would be to check EventQueue.isDispatchingThread
BEFORE you create the dialog... 最好的解决方案是在创建对话框之前检查
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);
}
}
As I said in you previous question, it should the responsibility of the caller to ensure that the code is executed correctly not your components. 正如我在上一个问题中所说,调用者应该负责确保代码正确执行而不是组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.