簡體   English   中英

確保在同一個(EDT)事件調度線程中

[英]Make sure in same (EDT) event dispatching thread

我有一個主要課程:

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);
    }
} 

正如我在上一個問題中所說,調用者應該負責確保代碼正確執行而不是組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM