简体   繁体   中英

Redirecting System.out.print(ln) to a textArea

I am redirecting System.out.print() to a JTextArea inside of a JScrollPane . This works fine except for one case as follows in this snippet:

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)   {
    }
}
...

Do I need to run something in the background on a separate Thread? Any ideas are appreciated.
Thanks.

Swing is a single threaded framework, this means that any operation which is run within the context of the Event Dispatching Thread, which is long running in nature or blocks for some reason (like I/O operations), will prevent the EDT from processing new events and update the UI.

See Concurrency in Swing for more details

If you're using something like How to set output stream to TextArea to redirect the System.out , then you could safely wrap the decryption process in some thing like a SwingWorker or other Thread , for example...

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;
    }

}

See Worker Threads and SwingWorker for more details...

Any changes in GUI should be ran in separate thread (in EDT to be exact) to prevent GUI freezes etc. In your case, this is what you are witness of - frozen GUI. In order to capture Sysout and see "live" updates, every text appending in your wrapper should be done via SwingUtilities.invokeLater()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM