【问题标题】:Make sure in same (EDT) event dispatching thread确保在同一个(EDT)事件调度线程中
【发布时间】:2013-05-02 02:11:43
【问题描述】:

我有一个主课:

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) 中的最佳方法是什么?

感谢您的任何回复。

【问题讨论】:

  • same 事件调度线程是什么意思?只有 1 个 EDT。 (或者我误解了你的真实问题)。
  • 我的意思是对于 InfoDialog,我没有在它的 initGUI 中调用 SwingUtilities.invokeLater。在这种情况下我需要这样做吗?
  • 我知道只有 1 个 EDT,我如何确保 InfoDialog 位于同一个 EDT 中。经过这么多小时的调试,我现在一定快疯了。

标签: java swing


【解决方案1】:

最好的解决方案是在创建对话框之前检查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);
    }
} 

正如我在上一个问题中所说,调用者应负责确保代码正确执行,而不是您的组件。

【讨论】:

  • 我已经在导致我所有问题的 handleTableRowOnClick() 方法中更新了我的问题。请查看该方法中的 cmets 。再次感谢您的帮助。
  • 感谢您的回答。我会试试这个。
  • 不幸的是,我已经尝试过了,但它不起作用。它仍然会挂起对话框并阻止后续执行。
  • @lcplusplus 然后在显示之前让您的对话框非模态:dialog.setModal(false),并确保在构造函数中提供适当的“父”Window,以避免“落后”效应。
  • 嗨,Guilluume,谢谢,我试过你的方法,效果很好。但是,问题是即使 JDialog 保持在前面,我仍然可以在父框架中使用控件(一次只能访问一个对话框)。如果您对此有解决方案,我将很高兴听到。但否则没关系,因为如果打开下一个对话框,我将关闭当前的 JDialog。再次感谢。
猜你喜欢
  • 2011-01-27
  • 1970-01-01
  • 2011-05-25
  • 2013-01-02
  • 2015-03-05
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
相关资源
最近更新 更多