SWT 定时器 update UI

SWT如果涉及到线程中的数据互访,在一个线程中的触发事性中再去访问另一个线程的数据,会报Invalid thread access的错误。

用SWT提供的display.asyncExec方法,SWT不是另开一个线程,只是把调用了run方法一次,所以当我们调用Thread.sleep或者后台程序运行时间比较久时程序就会死掉,即无响应。

使用定时器(线程实现)可以很好的解决UI update时候死掉的现象。 定时的通过外部发消息然后再去update UI.


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)});
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值