package components;import java.awt.*;
import java.awt.event.*;
import javax.swing.*;/* FrameDemo.java requires no other files. */
public class FrameDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); //Display the window.
frame.pack();
frame.setVisible(true);
} public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
这个是什么意思?
import java.awt.event.*;
import javax.swing.*;/* FrameDemo.java requires no other files. */
public class FrameDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); //Display the window.
frame.pack();
frame.setVisible(true);
} public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
这个是什么意思?
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
* 大概意思是说,创建GUI并显示它,为了线程安全,这个方法应该被一个event-dispatching线程调用。
*/然后最后就是创建这个线程,也有注释。// Schedule a job for the event-dispatching thread:
// 大致是说给这个线程分配一个工作,就是上面那个创建并显示GUI的工作。
读一下API就知道了,Warning: Swing is not thread safe.
Swing不是线程安全的,所以才为了线程安全这么做。
学GUI之前应该学了线程了吧,如果不知道什么是线程安全,可以回去再学一下线程这部分。
不建议使用单独的线程改变Swing的UI,
而Swing的主线程,如果在处理一些费时的事情的时候,
连续的更新UI的代码很可能会被错误处理,或者忽略这个时候又不建议使用单独线程,怎么办呢?
就用SwingUtilities.invokeLater把你想处理的事件排进Swing的主线程事件序列
这样在Swing处理完了其它事件就会正确来处理这段代码了