在 Java 中,我們如何呼叫 invokeLater() 方法?\n
**invokeLater()** 方法是 **SwingUtilities** 類的一個 **static** 方法,可用於在 **AWT** **事件分發執行緒**中 **非同步** 執行任務。**SwingUtilities.invokeLater()** 方法的工作原理與 **SwingUtilities.invokeAndWait()** 類似,只不過它將請求放在 **事件佇列** 中並 **立即返回**。**invokeLater()** 方法不會等待 **target** 引用的 **Runnable** 中的程式碼塊執行。
語法
public static void invokeLater(Runnable target)
示例
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InvokeLaterTest extends Object {
private static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}
public static void main(String[] args) {
final JLabel label= new JLabel("Initial text");
JPanel panel = new JPanel(new FlowLayout());
panel.add(label);
JFrame f = new JFrame("InvokeLater Test");
f.setContentPane(panel);
f.setSize(400, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
try {
print("sleeping for 5 seconds");
Thread.sleep(5000);
} catch(InterruptedException ie) {
print("interrupted while sleeping");
}
print("creating the code block for an event thread");
Runnable setTextRun = new Runnable() {
public void run() {
try {
Thread.sleep(100);
print("about to do setText()");
label.setText("New text");
} catch(Exception e) {
e.printStackTrace();
}
}
};
print("about to call invokeLater()");
SwingUtilities.invokeLater(setTextRun);
print("back from invokeLater()");
}
}輸出
main: sleeping for 5 seconds main: creating the code block for an event thread main: about to call invokeLater() main: back from invokeLater() AWT-EventQueue-0: about to do setText()
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP