日期:2014-05-20  浏览次数:20629 次

swing与SWT问题,欢迎高手来解决!
下面这个程序我用SWT写就不行,但是用swing就可以,为什么啊?
多谢高手们了
import   java.util.Timer;
import   java.util.TimerTask;

import   org.eclipse.swt.SWT;
import   org.eclipse.swt.layout.FillLayout;
import   org.eclipse.swt.widgets.Composite;
import   org.eclipse.swt.widgets.Display;
import   org.eclipse.swt.widgets.Label;
import   org.eclipse.swt.widgets.Shell;

public   class   MyTimerTest   {

/**
  *   Launch   the   application
  *   @param   args
  */
public   static   void   main(String[]   args)   {
final   Display   display   =   Display.getDefault();
final   Shell   shell   =   new   Shell();
shell.setLayout(new   FillLayout());
shell.setSize(500,   375);
shell.setText( "SWT   Application ");
//

shell.open();

final   Composite   composite   =   new   Composite(shell,   SWT.NONE);

final   Label   label   =   new   Label(composite,   SWT.NONE);
// label.setText( "Label ");
Timer   timer=new   Timer();
TimerTask   myTimer=new   MyTimer(label);
timer.schedule(myTimer,   0,   1000);
label.setBounds(33,   159,   120,   30);
shell.layout();
while   (!shell.isDisposed())   {
if   (!display.readAndDispatch())
display.sleep();
}
}

}

import   java.text.SimpleDateFormat;
import   java.util.Date;
import   java.util.TimerTask;

import   org.eclipse.swt.widgets.Label;

public   class   MyTimer   extends   TimerTask{
Label   label;
/**
  *   @param   args
  */
public   MyTimer(Label   label){
this.label=label;
}
@Override
public   void   run()   {
while(true){
try{
Date   date=new   Date();
SimpleDateFormat   df=new   SimpleDateFormat( "yyyy-MM-dd   HH:mm:ss ");
label.setText(df.format(date));
}catch(Exception   e){
e.printStackTrace();
}
}
}
}

------解决方案--------------------
这是swt的安全机制,附线程不能改变主线程中的widget,但是其他java数据却可以,所以你只能通过附线程改变主线程的数据,不能改变widget,widget只有主线程能控制。
------解决方案--------------------
是一楼说的原因。另外,他说的这个主线程通常叫做用户线程,在这个线程中可以进行UI更新,如果非要在非用户线程中操作图形控件,可以使用Display提供的两个方法,syncExec(Runnable)和asyncExec(Runnable),分别是同步异步执行一个线程。