需求 :最近在项目中使用 SWT时 ,需要在启动时加载较大的数据量,所以启动时间较慢。为了实现用户等待的友好界面,因此打算在启动画面时,同时加载数据,达到一个平缓的过渡。
原理:使用SWT的DIsplay类的异步方法,异步执行一个线程,该线程在记载数据的同时,实现进度条滚动,最后打开主页面 。
实现:使用抽象类实现,可以在多个应用中同时使用,主界面实现该抽象类即可 。
缺点: 滚动条滚动值需自行实现,滚动条不是很平滑。
public abstract class Splash {
/**
* Create contents of the window
*/
// 在进度条时加载后台数据。
public abstract void loadData(ProgressBar bar); // 滚动条滚动值需自行实现
// 执行显示主页面
public abstract void openMain(Image titleImage);
public void createContents(Display display) {
// 启动页面
final Image image = new Image(display, this .getClass().getResourceAsStream( " /wait.jpg " ));
final Image titleImage = new Image(display, this .getClass().getResourceAsStream( " /eclipse32.gif " ));
final Shell splashShell = new Shell(SWT.ON_TOP);
final ProgressBar bar = new ProgressBar(splashShell, SWT.NONE);
final Color color = Display.getCurrent()
.getSystemColor(SWT.COLOR_GREEN);
bar.setMinimum( 0 );
bar.setMaximum( 100 );
bar.setForeground(color);
final Label label = new Label(splashShell, SWT.NONE);
label.setImage(image);
FormLayout layout = new FormLayout();
splashShell.setLayout(layout);
FormData labelData = new FormData();
labelData.right = new FormAttachment( 100 , 0 );
labelData.bottom = new FormAttachment( 100 , 0 );
label.setLayoutData(labelData);
FormData progressData = new FormData();
progressData.left = new FormAttachment( 0 , 5 );
progressData.right = new FormAttachment( 100 , - 5 );
progressData.bottom = new FormAttachment( 114 , - 35 );
bar.setLayoutData(progressData);
splashShell.pack();
Rectangle splashRect = splashShell.getBounds();
Rectangle displayRect = display.getBounds();
int x = (displayRect.width - splashRect.width) / 2 ;
int y = (displayRect.height - splashRect.height) / 2 ;
splashShell.setLocation(x, y);
splashShell.open();
display.asyncExec( new Runnable() { // 异步执行一个线程
public void run() {
for ( int i = 1 ; i < 2 ; i ++ ) {
try {
Thread.sleep( 1000 );
} catch (Throwable e) {
}
loadData(bar);
}
splashShell.close();
color.dispose();
image.dispose();
// 主页面
openMain(titleImage);
}
});
}
}