Display CMD output in my GUI (java)

How can I get output from a CMD process to display in my GUI? This is the code I use to start 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 tried to do this:

jLabel1.setText(line);

... but the GUI is completely blocked during the process, so nothing is updated to the very end, which is not very useful. In addition, CMD works fine. I just want to display the output in real time.

+5
source share
3 answers

Did you redraw () after setting the label text?

, , , GUI. SwingWorker.

+5

. , , ( Runnable 's) run() , JLabel, - :

...
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: : , SwingWorker , ( Java).

: , , SwingWorker .

+3

In addition to what others have been talking about multithreading, you will also want to read the error stream of the child process. I believe that (in some cases), if you do not drain the stream of errors for the process, this can lead to a hang.

+2
source

All Articles