2011-05-05 42 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

相关问题