我做一个GUI的程序,基于eclipse  swt,要N秒执行一次任务调度,
要在GUI的TEXT上显示,执行代码时报错:Exception in thread "Timer-0" org.eclipse.swt.SWTException: Invalid thread access
public class SystemTray extends Shell{
public static void main(String[] args) {
//......
}
 Text t;
  public void controlInit(SystemTray shell){
          shell.setLayout(new GridLayout(1, false));       
  new Text(shell, SWT.READ_ONLY).setText("实时数据运行情况!");
       // 创建多行Text组件,包含边框,自动换行,包括垂直滚动条
          t = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.WRAP| SWT.V_SCROLL);
          t.setLayoutData(new GridData(GridData.FILL_BOTH));
          t.setText("信息: 获取实时数据时间");
          
          new Text(shell, SWT.READ_ONLY).setText("异常");
          Text text_exception = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.WRAP| SWT.V_SCROLL);
          text_exception.setLayoutData(new GridData(GridData.FILL_BOTH));
  }
  
   // 添加托盘右键菜单         
        final Menu menu = new Menu(shell, SWT.POP_UP);         MenuItem menuItemMaximize = new MenuItem(menu, SWT.PUSH);// 启动程序         
        menuItemMaximize.setText("采集数据...");
        menuItemMaximize.addSelectionListener(new SelectionListener() {
            public void widgetSelected(SelectionEvent e) {
             is=0;
             t.append("采集数据!");
             Timer timer=new Timer();
             TimerTask task=new ListingTimerStock(t);
             timer.schedule(task, 6000);
        
            }
}
public class ListingTimerStock extends TimerTask{ private Text text=null;
public ListingTimerStock(Text text){
System.out.println("构造函数!");
this.text=text;
}
public void run(){
 text.append("hello.....");
}
}

解决方案 »

  1.   

    不能这样子做,所有的GUI操作都要交给GUI线程去做,你把text.append...那一句改成Display.getCurrent().runAsync(new Runnable(){public void run(){text.append....}})应该就可以了
      

  2.   

    这类改了后,信息有显示出来,不过发现没有每隔N秒后再此执行public class ListingTimerStock extends TimerTask{    private Text text=null;
        public ListingTimerStock(Text text){
            System.out.println("构造函数!");
            this.text=text;    
            }
            public void run(){    
                 Display.getDefault().asyncExec(new Runnable(){
         public void run(){  
          text.setText("股票信息!");
                          }
    });        }
    }
      

  3.   

    我觉得楼上这样应该可以了吧,莫非TimerTask的调度机制会和SWT的发生冲突
      

  4.   

    你是说外围的run没被执行还是里面的没被执行?如果是里面没执行,你可以试下将asyncExec改成syncExec再试下,至少我原来试过这样子是没有问题的!
      

  5.   

    外围和内围的run都有被执行一次,不过没有定时的执行
    Timer timer=new Timer();
      TimerTask task=new ListingTimerStock(t);
      timer.schedule(task, 6000);  //每隔6秒钟执行一次,无法实现????
    synExec()试过也是不行
      

  6.   

    哈哈,问题解决,多谢各位
    原来是这里写错了timer.schedule(task,0 6000);