1

I have to execute a shell commande windows from java swing app and get real time result :

String cmd = jTextField1.getText();

StringBuffer output = new StringBuffer();

Process p;
try {
    p = Runtime.getRuntime().exec(cmd);

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    while ((line = reader.readLine()) != null) {
        System.out.println("" + line);
        jTextArea1.append(line + "\n");
    }

} catch (Exception e) {
    e.printStackTrace();
}

the problem is that writing in jTextArea is after execute finish not real time like System.out.println(..) .

Yaz
  • 492
  • 1
  • 6
  • 20

2 Answers2

4

When you update swing components from outside the Event Dispatch Thread (EDT) you should use either a SwingWorker or call SwingUtilities.invokeLater() like this:

while ((line = reader.readLine()) != null) {
    final String appendLine = line + "\n";
    System.out.println("" + line);
    SwingUtilities.invokeLater(new Runnable(){ 
        public void run(){    
            jTextArea1.append(appendLine);
        }
    });
} 
ospf
  • 169
  • 9
0

Try creating a Thread and use Thread.sleep() to do the live updating of the JTextArea.

Create a subclass like following

class Work implements Runnable {

        String cmd;

        Work(String c) {
            this.cmd = c;
        }

        @Override
        public void run() {
            Process p;
            try {
                p = Runtime.getRuntime().exec(cmd);

                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

                String line = "";
                while ((line = reader.readLine()) != null) {
                    System.out.println("" + line);
                    Thread.sleep(500);
                    jTextArea1.append(line + "\n");
                }

            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

Change the code as following

String cmd = jTextField1.getText();
StringBuffer output = new StringBuffer();
new Thread(new Work(cmd)).start()
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
  • 1
    This is incorrectly synchronized; a better approach is shown [here](http://stackoverflow.com/a/37859517/230513). – trashgod Jun 16 '16 at 16:27