0

I have a Java GUI application that runs some Python scripts and Linux applications. The code looks basically like this (can't post actual source due to policy):

private void runScript(ArrayList<String> aList)
{
    tA.append("Starting Process...");
    ProcessBuilder pb = new ProcessBuilder(aList);
    pb.redirectErrorStream(true);
    pb.redirectOutput();
    Process p = pb.start();
    tA.append("Process complete.");
}

where tA is a JTextArea in the main GUI and runScript is a method of the GUI class. The issue I'm having is that tA.append("Starting Process..."); doesn't seem to run before pb.start(); - nothing displays in the JTextArea until the Process is done executing. I've tried throwing a Thread.sleep(100) just after the first tA.append() but that doesn't seem to work. I have also tried this:

...
{
    syncrhonized(this)
    {
        tA.append("Starting Process...");
        <rest of code>
    }
}

but it still doesn't seem to populate the JTextArea before the process runs. Is there a way to enforce the sequential execution of these method calls?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Rob J.
  • 21
  • 2
  • 3
    You shouldn't call `pb.start()` in your main thread. That's causing the UI not to refresh until it finishes – Alberto S. Jul 10 '17 at 12:43
  • Are you doing this on the EDT? You should start your blocking process on a different thread. – matt Jul 10 '17 at 13:00
  • 2
    Maybe use a swing worker, https://stackoverflow.com/questions/10236995/how-do-i-make-my-swingworker-example-work-properly – matt Jul 10 '17 at 13:01
  • As the others are telling you, you're running long-running code *on* the Swing event thread. This blocks this key thread and prevents it from performing its necessary tasks, including drawing the GUI (including the contents of any text components) and interacting with the user. The solution is to run any long-running task **off** of this thread such as with a SwingWorker. To learn the details about this issue, please read: [Lesson: Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) – Hovercraft Full Of Eels Jul 10 '17 at 14:04
  • Thanks so much! I'll look into SwingWorker. – Rob J. Jul 10 '17 at 17:01

0 Answers0