import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class CountDownShell implements Runnable{
private static final int CountDownTime = 30; //倒計時,30秒
protected Shell shell;
private Thread clocker;
private Label countLabel;
public static void main(String[] args) {
try {
CountDownShell window = new CountDownShell();
window.open();
} catch(Exception e) {
e.printStackTrace();
}
}
public void open() {
Display display = Display.getDefault();
createContents();
centerShell(display, shell); //讓窗口居中顯示
shell.open();
shell.layout();
clocker = new Thread(this);
clocker.start();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
protected void createContents() {
shell = new Shell(SWT.NONE | SWT.APPLICATION_MODAL);
shell.setLayout(new GridLayout());
shell.setSize(228, 104);
shell.setText("SWT Dialog");
Composite panel = new Composite(shell, SWT.NONE);
panel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
panel.setLayout(gridLayout);
final Label label = new Label(panel, SWT.NONE);
label.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, true));
label.setText("倒計時:");
countLabel = new Label(panel, SWT.NONE);
countLabel.setText("30");
final Label label_2 = new Label(panel, SWT.NONE);
label_2.setText("秒");
}
public void run() {
int i = CountDownTime; //設置倒計時時間
while(i > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i--;
final int temp = i;
//在其他線程中調用UI線程(即修改界面元素),需要使用Display.getDefault().asyncExec()方法
Display.getDefault().asyncExec(new Runnable() {
public void run() {
countLabel.setText(temp + "");
}
});
}
Display.getDefault().asyncExec(new Runnable() {
public void run() {
//倒計時完成,退出窗口。
shell.dispose();
}
});
}
//居中顯示shell
private void centerShell(Display display, Shell shell) {
Rectangle displayBounds = display.getPrimaryMonitor().getBounds();
Rectangle shellBounds =shell.getBounds();
int x = displayBounds.x + (displayBounds.width - shellBounds.width)>>1;
int y = displayBounds.y + (displayBounds.height - shellBounds.height)>>1;
shell.setLocation(x, y);
}
}