要在后臺線程里對前臺界面組件進行訪問.
解決方法是使用Display對象,Display對象主要負責管理事件循環和控制UI線程和其它線程之間的通信.
Display.getDefault().asyncExec(new Runnable(){
});
- package com.tr069im.ui;
- import org.eclipse.swt.SWT;
- import org.eclipse.swt.layout.GridData;
- import org.eclipse.swt.widgets.Button;
- import org.eclipse.swt.widgets.Display;
- import org.eclipse.swt.widgets.MessageBox;
- import org.eclipse.swt.widgets.ProgressBar;
- import org.eclipse.swt.widgets.Shell;
- /**
- * 此類通過實現SWT滾動條,說明多線程問題 .解決了后臺線程訪問前臺界面的問題
- * @author llwbrothers
- */
- public class Login implements Runnable {
- private static Shell shell;
- private String loginResponse = "right";
- private static boolean flag = false;
- public Login() {
- }
- public static void main(String[] args) {
- final Display display = Display.getDefault();
- shell = new Shell(SWT.MIN);
- shell.setSize(290, 520);
- shell.setLocation(300, 5);
- shell.setText("SWT多線程");
- // 添加平滑的進度條
- final ProgressBar pb1 = new ProgressBar(shell, SWT.HORIZONTAL
- | SWT.SMOOTH);
- pb1.setBounds(72, 282, 160, 20);
- pb1.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- // 顯示進度條的最小值
- pb1.setMinimum(0);
- // 設置進度條的最大值
- pb1.setMaximum(30);
- // 登錄按鈕
- final Button btnLogin = new Button(shell, SWT.FLAT | SWT.PUSH);
- btnLogin.setBounds(80, 363, 111, 36);
- btnLogin.setText("取消");
- shell.open();
- // 異步線程處理其他數據
- display.asyncExec(new Runnable() {
- public void run() {
- Login pl = new Login();
- Thread t = new Thread(pl);
- t.start();
- }
- });
- // 添加線程,在線程中處理長時間的任務,并最終反映在平滑進度條上
- Runnable runnable = new Runnable() {
- public void run() {
- for (int i = 0; i < 30; i++) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- }
- display.asyncExec(new Runnable() {
- public void run() {
- if (pb1.isDisposed())
- return;
- // 進度條遞增
- pb1.setSelection(pb1.getSelection() + 1);
- }
- });
- if (flag) { // 作為標志,使滾動條起作用
- break;
- }
- if (i == 29) {
- open();
- }
- }
- }
- };// 啟動這個線程
- new Thread(runnable).start();
- while (!shell.isDisposed()) { // 如果主窗體沒有關閉
- if (!display.readAndDispatch()) { // 如果display不忙
- display.sleep(); // 休眠
- }
- }
- display.dispose(); // 銷毀display
- }
- public void run() {
- try {
- // 收到驗證信息后進行
- if (loginResponse.equals("right")) {
- // 后臺線程訪問前臺界面
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- flag = true;
- Shell shell = new Shell(SWT.MIN);
- MessageBox messageBox = new MessageBox(shell,
- SWT.ICON_WARNING);
- messageBox.setMessage("用戶名或密碼錯誤!");
- messageBox.open();
- }
- });
- } else {
- }
- } catch (Exception ee) {
- }
- }
- public static void open() {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- // 進度條進行完之后,執行的程序
- }
- });
- }
- }