将System.out.println重定向到textArea

时间:2014-10-14 03:31:54

标签: java swing jtextarea

我正在将System.out.print()重定向到JTextArea内的JScrollPane。这个工作正常,除了这个片段中的一个案例如下:

public void vcFile(){
System.out.println("In vcFile");    // THIS WORKS!
File[] files = getChooser("Select File(s)", JFileChooser.FILES_AND_DIRECTORIES, true);
if(files[0] != null)    {
    ...
    try {
        for(int j=0; j<files.length; j++)   {
            // SDencryptFiles() has System.out.println()'s in it, but
            // no System.out's show in the JScrollPane until after 
            // SDencryptFiles completes  I want then to appear as they
            // are executed
            SDencryptFiles(String, String, int);
        }   
    } catch (Exception e)   {
    }
}
...

我是否需要在单独的线程中在后台运行某些东西?任何想法都表示赞赏 感谢。

2 个答案:

答案 0 :(得分:2)

Swing是一个单线程框架,这意味着在事件调度线程的上下文中运行的任何操作,由于某种原因(如I / O操作)而在本质上长期运行或阻塞,将阻止EDT处理新事件并更新用户界面。

有关详细信息,请参阅Concurrency in Swing

如果您使用How to set output stream to TextArea之类的内容重定向System.out,那么您可以安全地将解密过程包装在SwingWorker或其他Thread之类的内容中,例如......

public class DecryptWorker extends SwingWorker {

    private File[] files;

    public DecryptWorker(File[] files) {
        this.files = files;
    }

    @Override
    protected Object doInBackground() throws Exception {
        if(files[0] != null)    {
            ...
            for (int j = 0; j < files.length; j++) {
                            // SDencryptFiles() has System.out.println()'s in it, but
                    // no System.out's show in the JScrollPane until after 
                    // SDencryptFiles completes  I want then to appear as they
                    // are executed
                    SDencryptFiles(String, String, int);
            }
        }
        return null;
    }

}

有关详细信息,请参阅Worker Threads and SwingWorker ...

答案 1 :(得分:1)

GUI中的任何更改都应该在单独的线程中运行(准确地说在EDT中)以防止GUI冻结等。在您的情况下,这是您见证的 - 冻结GUI。为了捕获Sysout并查看“实时”更新,您的包装中附加的每个文本都应通过SwingUtilities.invokeLater()

完成