Java 中 SwingUtilities 类的重要性是什么?
在 Java 中,Swing 组件显示在屏幕上后,只能由一个名为**事件处理线程**的线程操作。我们可以在单独的代码块中编写代码,并将此代码块的引用传递给**事件处理线程**。**SwingUtilities** 类有两个重要的静态方法,**invokeAndWait()** 和 **invokeLater()**,用于将代码块的引用放入**事件队列**。
语法
public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException public static void invokeLater(Runnable doRun)
参数 **doRun** 是 **Runnable** 接口实例的引用。在这种情况下,**Runnable** 接口不会传递给 Thread 的构造函数。**Runnable** 接口只是被用作标识事件线程入口点的一种方式。就像新生成的线程将调用 **run()** 一样,事件线程将在处理完队列中所有其他待处理事件后调用 **run()** 方法。如果在目标引用的代码块完成之前中断调用 **invokeAndWait()** 或 **invokeLater()** 的线程,则会抛出 **InterruptedException**。如果 **run()** 方法内部抛出未捕获的异常,则会抛出 **InvocationTargetException**。
示例
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");
}
}输出
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP