Java에서는 스윙 컴포넌트가 화면에 표시된 후 Event Handling Thread라는 하나의 스레드에서만 작동할 수 있습니다. . 별도의 블록에 코드를 작성할 수 있으며 이 블록에 이벤트 참조를 제공할 수 있습니다. 취급 스레드 . SwingUtilities 클래스에는 invokeAndWait()라는 두 가지 중요한 정적 메서드가 있습니다. 및 invokeLater() 이벤트 에 코드 블록에 대한 참조를 넣는 데 사용 대기열 .
구문
public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException public static void invokeLater(Runnable doRun)
매개변수 doRun 실행 가능 인스턴스에 대한 참조입니다. 상호 작용. 이 경우 실행 가능 인터페이스는 Thread의 생성자에 전달되지 않습니다. 실행 가능 인터페이스는 단순히 이벤트 스레드의 진입점을 식별하는 수단으로 사용됩니다. 새로 생성된 스레드가 run()을 호출하는 것처럼 , 이벤트 스레드는 run() 을 호출합니다. 방법 큐에 보류 중인 다른 모든 이벤트를 처리했을 때. InterruptedException invokeAndWait() 를 호출한 스레드가 있으면 throw됩니다. 또는 invokeLater() i 대상이 참조하는 코드 블록이 완료되기 전에 중단됩니다. InvocationTargetException run() 내부의 코드에서 잡히지 않은 예외가 발생하면 발생 방법.
예
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
public class SwingUtilitiesTest {
public static void main(String[] args) {
final JButton button = new JButton("Not Changed");
JPanel panel = new JPanel();
panel.add(button);
JFrame f = new JFrame("InvokeAndWaitMain");
f.setContentPane(panel);
f.setSize(300, 100);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println(Thread.currentThread().getName()+" is going into sleep for 3 seconds");
try {
Thread.sleep(3000);
} catch(Exception e){ }
//Preparing code for label change
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"is going into sleep for 10 seconds");
try {
Thread.sleep(10000);
} catch(Exception e){ }
button.setText("Button Text Changed by "+ Thread.currentThread().getName());
System.out.println("Button changes ended");
}
};
System.out.println("Component changes put on the event thread by main thread");
try {
SwingUtilities.invokeAndWait(r);
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread reached end");
}
} 출력

