Java Swing & Thread
Every Swing application has at least 2 threads:
- The main thread that executes the application
- The EDT (Event Dispatching Thread) is a thread that updates the UI (so the UI will not freeze).
If you want to update the UI you should execute code within the EDT. Methods like SwingUtilities.invokeLater, SwingUtilities.invokeAndWait, EventQueue.invokeLater, EventQueue.invokeAndWait allow you to execute code by the EDT.
Swing 프로그램에서 UI 를 갱신할 수 있는 쓰레드는 EDT 이므로 개발자가 정의한 쓰레드나 main 쓰레드에서 UI를 갱신하기 위해서는 아래의 코드처럼 invokeLater()를 이용하여 EDT에 의해 실행될 수 있도록 Runnable 인스턴스를 생성해주어야 한다
Runnable을 구현한 클래스의 run() 메소드는 쓰레드에 의해 실행될 수 있는 코드이므로 아래의 코드는 EDT에 의해 실행될 수 있다.
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyFrame().setVisible(true);
}
});
}