要在后台线程里对前台界面组件进行访问.
- 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() {
- // 进度条进行完之后,执行的程序
- }
- });
- }
- }