当前页面: 开发资料首页 → J2SE 专题 → 关于TimerTask和SWT的一个调用问题
关于TimerTask和SWT的一个调用问题
摘要: 关于TimerTask和SWT的一个调用问题
我做一个GUI的程序,基于eclipse swt,要10秒一次任务调度,要在GUI显示,可不可以这么用,是SWT线程模型导致的错误吗?
import org.eclipse.swt.widgets.Text;
public class ClientFrame{
private Text text=new ....;
................
public void func(){
text.append(-#34;hello-#34;);
Timer timer=new Timer();
TimerTask task=new MornitorData(text);
timer.schedule(task,0,10000);
}
}
other file:
public class MornitorData{
private Text text=null;
...................
public MornitorData(Text text){
this.text=text;
...........
}
public void run(){
text.append(-#34;hello-#34;);//此处异常 exception in thread -#34;Timer-0-#34;
org.eclipse.swt.SWTException:Invalid thread access
}
}
这个问题比较常见,swt有专门的例子讲述这个问题。
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
public class ProgressorBar {
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
ProgressBar bar = new ProgressBar (shell, SWT.SMOOTH);
bar.setBounds (10, 10, 200, 32);
shell.open ();
for (int i=0; i-#60;=bar.getMaximum (); i++) {
try {Thread.sleep (100);} catch (Throwable th) {}
bar.setSelection (i);
}
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}
看看SWT线程