0

I have a Swing button with an actionPerformed event that downloads a file, when it is clicked it calls:

private static void updateTextArea(final String text) {
    textArea.append(text + "\n");
    textArea.setCaretPosition(textArea.getDocument().getLength());
}

And then calls:

public static void download(String fileName, String url) throws IOException {
     URL link = new URL(url);
     InputStream in = new BufferedInputStream(link.openStream());
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     byte[] buf = new byte[1024];
     int n = 0;
     while (-1!=(n=in.read(buf)))
     {
        out.write(buf, 0, n);
     }
     out.close();
     in.close();
     byte[] response = out.toByteArray();

     FileOutputStream fos = new FileOutputStream(fileName);
     fos.write(response);
     fos.close();
}

The file downloads as intended, my problem is that the textArea updates AFTER the file is finished downloading, but I want it to update as soon as I cal updateTextArea("").

How to ensure the text area is updated before the long running process?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Socratic Phoenix
  • 556
  • 1
  • 7
  • 19
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) Don't block the EDT (Event Dispatch Thread). The GUI will 'freeze' when that happens. See [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for details and the fix. – Andrew Thompson Jan 18 '15 at 02:45
  • Your code is not nearly complete enough for most of us mortals to guess what could be wrong, so yes, follow @Andrew's suggestion to give us a more complete view of your problem. Also, those methods should not be static. While this may not be the cause of your current problem, it will be the cause of future problems. – Hovercraft Full Of Eels Jan 18 '15 at 02:47
  • 1
    You're blocking the Event Dispatching Thread, preventing from updating the UI. See [Concurrency in Java](http://docs.oracle.com/javase/tutorial/essential/concurrency/) and [Worker Threads and SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) for details and [this examples](http://stackoverflow.com/questions/13694357/display-in-jtextarea-when-copying-is-in-progress/13694483#13694483) for ideas to solve it... – MadProgrammer Jan 18 '15 at 02:48

0 Answers0