2011-05-05 41 views
1

我想用啓動和停止進程按鈕來創建GUI。在點擊開始按鈕時,一個進程啓動,當用戶點擊停止按鈕時,它應該停止正在運行的進程,但是當進程開始控制時,不會返回到原始GUI。 任何人都可以有解決方案嗎? 代碼片段如下: -java-如何停止點擊按鈕上的進程

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {           
    // TODO add your handling code here: 
      try { 
     jTextArea1.setText("\nC:\\peach\\peach.bat --debug "+jFormattedTextField4.getText()+"\n\n"); 
    if(jFormattedTextField4.getText().isEmpty()){ 
     JOptionPane.showMessageDialog(null, "Browse The Peach File First"); 
    } 
    else 
    { 

      String line=new String(jFormattedTextField4.getText()); 
    OutputStream stdin = null; 
    InputStream stderr = null; 
    InputStream stdout = null; 

    // launch EXE and grab stdin/stdout and stderr 
    //process = Runtime.getRuntime().exec("C:\\peach\\peach.bat --debug "+line); 
    stdin = process.getOutputStream(); 
    stderr = process.getErrorStream(); 
    stdout = process.getInputStream(); 
    stdin.close(); 

    // clean up if any output in stdout 
    BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout)); 
     while ((line = brCleanUp.readLine()) != null) { 
      System.out.println ("[Stdout] " + line); 
          jTextArea1.append("[Stdout]-->"+line+"\n"); 
     } 
    brCleanUp.close(); 

      // clean up if any output in stderr 
    brCleanUp = new BufferedReader (new InputStreamReader (stderr)); 
     while ((line = brCleanUp.readLine()) != null) { 
     System.out.println ("[Stderr]-->" + line); 
        jTextArea1.append("[Stderr]"+line+"\n"); 
     } 
    brCleanUp.close(); 

    } 

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

}

私人無效jButton6ActionPerformed(EVT java.awt.event.ActionEvent中){
// TODO添加處理代碼在這裏:

process.destroy();  

}

回答

1

以下行:

while ((line = brCleanUp.readLine()) != null) { 

等待stdout流的結束。當您等待子進程stdout的結束時,程序將不會繼續,因此您的事件循環未運行,您將無法再按任何其他按鈕。

要解決此問題,您需要定期從brCleanUp中讀取數據,同時仍然讓GUI事件循環運行。

1

作爲一般規則,您不想在Swing事件派發線程上執行任何長時間運行的任務;你會想要從美國東部時間的輸入中移動你的閱讀。一種可能性是使用SwingWorker

相關問題