在GUI中动态更新JTextArea

时间:2014-08-20 23:22:49

标签: java multithreading swing jtextarea swingworker

我正在尝试动态更新JTextArea,我目前的代码如下:

Object buttonPressed = e.getSource();
if (buttonPressed.equals(uploadSend)){
 new Thread(){

   @Override public void run(){
  Upload send = new Upload();
  send.sendupload();
   for (String rec : uploadList.getUploadDetails()) {                 
       uploadDetails.append(rec.toString());
       uploadDetails.append("\n");
   }
}     
 }.start();
}

这可以通过在按下JButton并且JButton不再冻结时发送theupup来实现,但是在整个上传任务完成之前,JTextArea中的文本仍然没有显示。

我已经阅读了有关SwingWorker的内容,这是我所缺少的,我将如何实现这一点?

1 个答案:

答案 0 :(得分:4)

很难知道为什么您的文字区域没有更新,因为您没有提供足够的上下文来诊断问题,请考虑提供一个runnable example来证明您的问题。这将减少混淆和更好的响应

但是,如果您想将当前逻辑转换为使用SwingWorker,您可以使用类似......

public class UploadWorker extends SwingWorker<List<String>, String> {

    @Override
    protected List<String> doInBackground() throws Exception {
        Upload send = new Upload();
        send.sendupload();
        for (String rec : uploadList.getUploadDetails()) {
            publish(rec);
        }
        return uploadList.getUploadDetails();
    }

    @Override
    protected void process(List<String> chunks) {
        for (String text : chunks) {
            uploadDetails.append(rec);
            uploadDetails.append("\n");
        }
    }

}

然后你只需要用......之类的东西来调用它。

if (buttonPressed.equals(uploadSend)){
    UploadWorker worker = new UploadWorker();
    worker.execute();
}

请查看Worker Threads and SwingWorker了解详情