如何在Eclipse插件中使用Timer和SwingWorker?

时间:2015-06-10 13:48:42

标签: java eclipse eclipse-plugin

我正在开发一个Eclipse插件,它将通过视图为GUI做出贡献。

当用户在工作区中选择文件夹或文件时,视图会使用版本控制系统中的信息进行更新。

为了避免每次用户浏览项目子文件夹和文件时收集数据,我需要等待3秒才能确保文件或文件夹是您感兴趣的文件或文件夹。

我目前正在使用Swing Timer进行此操作。

这适用于少量数据,但对于大量数据,GUI会阻塞,等待定时器执行更新功能。

我知道这项任务我可以使用SwingWorker,但我无法弄清楚如何延迟任务并在需要时重新启动延迟。

有人能给我一个如何正确解决这个问题的解决方案吗?

这是我目前的代码:

  public void resetTimerIfNeeded()
    {
        if(timer.isRunning())
            timer.restart();
        else
            timer.start();
    }


    public void timer()
    {
        selectionTimer = new Timer(3000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub


                Display.getDefault().syncExec(new Runnable(){
                    @Override
                    public void run()
                    {               
                        updateView();
                        selectionTimer.stop();                  
                    }
                }); 
            }
        });
    }

2 个答案:

答案 0 :(得分:1)

由于Eclipse使用SWT而不是Swing,因此最好避免使用Swing代码。

使用UIJob延迟后,您可以在UI线程中运行代码,例如:

UIJob job = new UIJob("Job title") {
        @Override
        public IStatus runInUIThread(IProgressMonitor monitor) {

            updateView();

            return Status.OK_STATUS;
        }
    };

job.schedule(3000);

或者,您可以使用Display.timerExec

Display.getDefault().timerExec(3000, new Runnable(){
         @Override
         public void run()
         {               
           updateView();
         }
    });

答案 1 :(得分:0)

将其安排为工作:https://eclipse.org/articles/Article-Concurrency/jobs-api.html。如果UIJob的全部内容与UI交互,请使用UIJob。取消/调度和睡眠/唤醒方法将是有意义的,请参阅http://help.eclipse.org/luna/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/jobs/Job.html以获取JavaDoc。