1

My project aims to integrate a terminal into a Swing App. The problem is that some blocking commands are blocking the stream. That is why I would like to read with a buffer into the Standard output with a thread in order to "unblock" the input stream.

My question is similar to this topic, Why is my JTextArea not updating?

I apply what they said: using a thread in order to update my JTextArea.

public void appendNewText(String line) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                outputComponent.setText(outputComponent.getText() + line + "\n");
            }
        });
    }
    this.outputComponent.setText("");
    processBuilder.command(shell, "-c", inputComponent.getText());
    Process process = processBuilder.start();
    InputStream inputStream = process.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    while ((line = br.readLine()) != null)
        appendNewText(line);

    exitValue = process.waitFor();

Why is it not updating now? I'm suspicious about this:

exitValue = process.waitFor();
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
hugo GDRM
  • 31
  • 4
  • 3
    Your code is NOT executing on a separate Thread. The comment in that posting is correct. Using that code will make sure your code executes on the Event Dispatch Thread (EDT) which will prevent the GUI from repainting itself. Use a `SwingWorker`. Then you can `publish()` the results as they become available. Read the section from the Swing tutorial on [Concurrency](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more information and examples, especially the section on `Tasks That Have Interim Results`. – camickr Jun 15 '21 at 23:02
  • 1
    `outputComponent.setText(outputComponent.getText() + line + "\n");` Note that `JTextArea` has an `append(..)` method. – Andrew Thompson Jun 16 '21 at 00:15
  • [For example](https://stackoverflow.com/questions/15801069/printing-a-java-inputstream-from-a-process/15801490#15801490) – MadProgrammer Jun 16 '21 at 01:24

0 Answers0