为什么 JFrame 在不同的 Thread 中实例化
Why is JFrame instantiated in a different Thread
我不明白幕后到底发生了什么。
如果我有一个像下面这样的主要方法,是否意味着我有 2 个线程?
一个主线程和一个用于诸如 paintComponent 或侦听器等事件的线程?
如果是这样,那么主线程中到底发生了什么?
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ampelsteuerung frame = new Ampelsteuerung();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}`
我删除了 EventQueue 并在没有的情况下对其进行了测试,看不出有什么不同。
如果您阅读 SwingUtilities.invokeLater() 的说明,您就会明白其中的原因。这都是关于 AWT 事件和 GUI 线程之间的同步
This will happen after all pending AWT events have been processed.
This method should be used when an application thread needs to update
the GUI....If invokeLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the doRun.run() will still be deferred until all pending events have been processed
因此,如果没有像您的情况那样存在未决事件,"nothing" 似乎会发生。
我不明白幕后到底发生了什么。
如果我有一个像下面这样的主要方法,是否意味着我有 2 个线程? 一个主线程和一个用于诸如 paintComponent 或侦听器等事件的线程? 如果是这样,那么主线程中到底发生了什么?
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ampelsteuerung frame = new Ampelsteuerung();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}`
我删除了 EventQueue 并在没有的情况下对其进行了测试,看不出有什么不同。
如果您阅读 SwingUtilities.invokeLater() 的说明,您就会明白其中的原因。这都是关于 AWT 事件和 GUI 线程之间的同步
This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI....If invokeLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the doRun.run() will still be deferred until all pending events have been processed
因此,如果没有像您的情况那样存在未决事件,"nothing" 似乎会发生。