列如GUI加载图形文件,there may be a delay before the GUI appears;
如果该图形文件时加载的调度线程,图形用户界面可能暂时无法响应用户。
为了避免这些问题, TumbleItem
创建并执行一个实例 SwingWorker
从最初的线程。
该对象的 doInBackground
方法,在辅助线程中执行,加载到一个图像 ImageIcon
数组,并返回对它的引用。
然后 done()
方法在事件派发线程中执行,调用 done()
检索此引用,它分配给一个applet类字段名为 imgs
。
这使得 TumbleItem
构建图形用户界面立即加载,无需等待图像完成。
下面的代码是定义和执行 的SwingWorker
对象。
SwingWorker worker = new SwingWorker<ImageIcon[], Void>() {
@Override
public ImageIcon[] doInBackground() {
final ImageIcon[] innerImgs = new ImageIcon[nimgs];
for (int i = 0; i < nimgs; i++) {
innerImgs[i] = loadImage(i+1);
}
return innerImgs;
}
@Override
public void done() {
//Remove the "Loading images" label.
animator.removeAll();
loopslot = -1;
try {
imgs = get();
} catch (InterruptedException ignore) {}
catch (java.util.concurrent.ExecutionException e) {
String why = null;
Throwable cause = e.getCause();
if (cause != null) {
why = cause.getMessage();
} else {
why = e.getMessage();
}
System.err.println("Error retrieving file: " + why);
}
}
};
process()
is only interested in the last value reported each time, using it to update the GUI
process()方法在加载时执行,用于更新界面。