---
title: "SWT 定时器 update UI"
author: "royzhou1985"
date: "2010-11-30T17:00:40Z"
tags: ["Access", "Eclipse", "UI", "thread"]
categories: ["编程语言"]
slug: "swt-update-ui"
draft: false
lastmod: "2010-11-30T17:01:52Z"
id: 829507
url: "https://royzhou1985.iteye.com/blog/829507"
---

SWT如果涉及到线程中的数据互访，在一个线程中的触发事性中再去访问另一个线程的数据，会报Invalid thread access的错误。

用SWT提供的display.asyncExec方法，SWT不是另开一个线程，只是把调用了run方法一次，所以当我们调用Thread.sleep或者后台程序运行时间比较久时程序就会死掉，即无响应。

使用定时器（线程实现）可以很好的解决UI update时候死掉的现象。 定时的通过外部发消息然后再去update UI.


```java

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

public class Main {
	public static int counter;

	public static void main(String[] args) {
		final Display display = new Display();
		final Shell shell = new Shell();
		shell.setLayout(new FillLayout());
		shell.setText("Counter");
		
		final Table table = new Main().createTable(shell);
		
		shell.open();
		Thread MyThread = new Thread() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						return;
					}
					display.asyncExec(new CMD(table));
				}
			}
		};
		MyThread.start();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		MyThread.interrupt();
	}
	
	public Table createTable(final Shell shell) {
		Table table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		table.setBounds(40, 30, 723, 290);

		TableColumn tc1 = new TableColumn(table, SWT.LEFT);
		tc1.setText("Column1");
		tc1.setWidth(50);

		TableColumn tc2 = new TableColumn(table, SWT.LEFT);
		tc2.setText("Column2");
		tc2.setWidth(200);

		TableColumn tc3 = new TableColumn(table, SWT.LEFT);
		tc3.setText("Column3");
		tc3.setWidth(400);
		
		for(int i=0; i<10; i++) {
			TableItem ti = new TableItem(table, SWT.BORDER);
			ti.setText(new String[] {(i+1)+"","Column2:value" + (i+1),"Column3:value" + (i+1)});
		}
		return table;
	}
}

class CMD implements Runnable {
	private Table table;
	
	public CMD(Table table) {
		this.table = table;
	}

	public void run() {
		if(Main.counter<table.getItems().length) {
			TableItem ti = table.getItem(Main.counter++);
			ti.setText(new String[] {ti.getText(0), "updated " + ti.getText(1), "updated " + ti.getText(2)});
		}
	}
}

```