2016-06-16 10 views
1

上のシェルコマンドからの結果を得る:私はJavaのスイングアプリからシェルcommandeウィンドウを実行し、リアルタイムで結果を取得する必要がJTextAreaに

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

問題は次のようにJTextAreaの中での書き込みが後の仕上がり本物ではない時間を実行していることですSystem.out.println(..)。

答えて

4

を以下のように変更

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

    } 

を次のようにサブクラスを作成します。 SwingUtilities.invokeLater()のように:

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

スレッドを作成し、Thread.sleep()を使用してJTextAreaのライブアップデートを実行してください。

あなたはSwingWorkerのか、呼び出しのどちらかを使用する必要があるコードを使用すると、イベントディスパッチスレッド(EDT)外部からのSwingコンポーネントを更新すると

String cmd = jTextField1.getText(); 
StringBuffer output = new StringBuffer(); 
new Thread(new Work(cmd)).start() 
+1

これは間違って同期されています。より良いアプローチが示されている[ここ](http://stackoverflow.com/a/37859517/230513)。 – trashgod

+0

@trashgod正しく動作していますが最適化されていません! – Yaz

+0

ヤズ:悲しいことに、それは信頼できません(http://stackoverflow.com/a/7158505/230513)。 – trashgod

関連する問題