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(..) .

2 Answers 2

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); } }); } 
Sign up to request clarification or add additional context in comments.

Comments

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() 

1 Comment

This is incorrectly synchronized; a better approach is shown here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.