2010-06-06 66 views
1

我有一个带有IOBound任务的SwingWorker线程,它在运行时完全锁定了接口。换出计数器循环的正常工作负载具有相同的结果。该SwingWorker的基本上是这样的:为什么我的GUI在SwingWorker线程运行时没有响应?

public class BackupWorker extends SwingWorker<String, String> { 

private static String uname = null; 
private static String pass = null; 
private static String filename = null; 
static String status = null; 

BackupWorker (String uname, String pass, String filename) { 
    this.uname = uname; 
    this.pass = pass; 
    this.filename = filename; 
} 

@Override 
protected String doInBackground() throws Exception { 
      BackupObject bak = newBackupObject(uname,pass,filename); 
    return "Done!"; 
} 

}

那踢它关闭生活在扩展JFrame的一类代码:

public void actionPerformed(ActionEvent event) { 
    String cmd = event.getActionCommand(); 

    if (BACKUP.equals(cmd)) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 

       final StatusFrame statusFrame = new StatusFrame(); 
       statusFrame.setVisible(true); 

       SwingUtilities.invokeLater(new Runnable() { 
        public void run() { 
         statusFrame.beginBackup(uname,pass,filename); 
        } 
       }); 
      } 
     }); 
    } 
} 

这里的StatusFrame的有趣的部分:

public void beginBackup(final String uname, final String pass, final String filename) { 
    worker = new BackupWorker(uname, pass, filename); 
    worker.execute(); 

    try { 
     System.out.println(worker.get()); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } 
} 

}

就我所知,所有“长时间运行”的工作都由工作人员处理,而所有触及EDT上的GUI。我是否将某些事情纠缠在一起,还是我期望SwingWorker太多?

回答

6

我认为这个问题是由于您在beginBackup方法中调用SwingWorker.get()造成的。看看在docs for this method

如有必要,等待计算 完成,然后获取其 结果。

这是一个阻塞呼叫,因此您的GUI变得无法响应。

(此外,有没有你为什么这样做从01​​呼叫内的invokeLater?你已经在美国东部时间运行的任何特别的原因。)

+0

把我扔到这里的是在'get()'之前用'while(!worker.isDone())'看到同样的无反应。 我在'StatusFrame'完成绘图之前看到GUI锁定,直到我尝试了难看的'Runnable'嵌套。这个问题现在是有争议的。 – Starchy 2010-06-06 17:50:46

0

阅读从Swing教程中的部分上Tasks That Have Interim Results了工作示例。您将看到get(...)方法是从在SwingWorker类中重写的process(...)方法内调用的。

相关问题