我在我的應用程序的主JFrame上有一個Window Listener。我在應用程序中的按鈕上也有一個按鈕監聽器。我用這個作爲按鈕偵聽模式:Swing Window監聽器線程問題
good.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
// We're going to do something that takes a long time, so we
// spin off a thread and update the display when we're done.
Thread worker = new Thread() {
public void run() {
// Report the result using invokeLater().
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for(int i=0; i<1000000; i++){
System.out.println("foo");
}
}
});
}
};
worker.start(); // So we don't hold up the dispatch thread.
}
});
當我按一下按鈕,我看到每個迭代的打印輸出,但窗口監聽器不會被觸發後纔會循環完成執行。 print'foo'只是爲了模擬一些需要一段時間的事情,我希望一旦窗口事件發生(這可能在run()方法執行過程中的某個地方)就會觸發監聽器,但它好像它沒有被觸發,直到for循環結束。
任何想法爲什麼?
我的代碼是爲線程內部的動作偵聽器運行的。這不是你指的是什麼? – user1154644
它位於線程內部,但線程僅使用SwingUtilities將該操作分派給EDT。目前還不清楚你究竟在做些什麼,但也許你想要在線程內部循環,以及在EDT上進行每次迭代更新。 – copeg