views:

1755

answers:

4

How might I get the output from a CMD process to display in my GUI? This is the code I'm using to run the process:

try {
    String line;
    Process p = Runtime.getRuntime().exec("cmd /c \"e:\\folder\\someCommands.cmd\"");
    BufferedReader input =
            new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
        System.out.println(line);
    }
    input.close();
} catch (Exception err) {
    err.printStackTrace();
}

I've tried doing this:

jLabel1.setText(line);

...but the GUI is completely locked up while the process is running, so nothing updates until the very end, which isn't very useful. Other than that the CMD works fine. I just want to display the output in real-time.

+4  A: 

Did you repaint() after setting the text of the label?

Anyway, you should generally be hesitant to execute a long operation on the GUI event thread. Look into using a SwingWorker instead.

Michael Myers
+2  A: 

You'll need to start a separate thread to run the process. The code you're using to run it can mostly just be inserted into the thread's (or Runnable's) run() method as is, but to set the text in the JLabel, you should use something like this:

...
while ((line = input.readLine()) != null) {
    SwingUtilities.invokeLater(new SetTextRunnable(jLabel1, line));
}
...

class SetTextRunnable implements Runnable {
    private String line;
    private JLabel jLabel1
    public SetTextRunnable(JLabel jLabel1, String line) {
        this.jLabel1 = jLabel1;
        this.line = line;
    }
    public void run() {
        jLabel1.setText(line);
    }
}

EDIT: just noticed something: apparently the class SwingWorker was designed for this sort of thing, so that's another option for you (if it exists in your version of Java).

EDIT to the EDIT: so silly me, I didn't notice SwingWorker was already mentioned in another answer.

David Zaslavsky
or just put the code to read the process' stream into a separate thread. For example, you might want another thread that reads the error stream.
dotjoe
+2  A: 

In addition to what others have said about multithreading this - you'll also want to read the child process error stream. I believe that (in some instances) if you don't drain the error stream for the process it could cause it to hang.

Eric Petroelje