Discussion Locked

getting stdout into Swing textArea

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I am trying to run unix operating system command or shell script within my java program and get the stdout displayed into my textArea. It works fine. The problem I am having is I don't get anything show up on my textArea until all the output is ready. In other words, if the output lasts two minutes, and if I send the output to Systen.out.println(s) I get the output line by line, the way I want it, but if I try to get it into my textArea I have to wait for two minutes, and I get all output at once.

Here is my code

Process p = Runtime.getRuntime().exec(l);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null)
{
pane.append(s);
pane.append("\");
}

5 replies

by paul field

Are you running this code as a result of something happing in the user interface (e.g. a button being pressed)? If so, your code will lock the Swing event processing thread until your process is finished - you should find that none of your GUI worksuntil the process is finished.

If that's the case, you need to create a new thread and run your code in that. Beware though - Swing is not thread-safe so you have to be careful when calling Swing methods from other threads.

Your code might look like this:

// Run your code in a new thread (uses an
anonymous inner class)

new Thread() {
public void run() {
runProcess();
}
}.start();

.......

private void startProcess() {
// Your code
Process p = Runtime.getRuntime().exec(l);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null)
{
safeAppend(s);
}
}

private void safeAppend(final String s) {
Runnable appendToPane = new Runnable(){
public void run() {
pane.append(s)
pane.append("\");
}
};

SwingUtilities.invokeLater(appendToPane);
}

This discussion is closed to new replies.