Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display CMD output in my GUI (java)

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.

like image 348
Glenn Avatar asked Mar 20 '09 18:03

Glenn


2 Answers

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.

like image 153
Michael Myers Avatar answered Sep 30 '22 18:09

Michael Myers


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.

like image 34
David Z Avatar answered Sep 30 '22 17:09

David Z