SWT下一個簡單的倒計時窗口

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);
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值