【问题标题】:java- how to stop process on button clickingjava-如何在单击按钮时停止进程
【发布时间】:2011-08-19 06:13:10
【问题描述】:

我正在尝试使用开始和停止进程按钮创建 GUI。单击开始按钮时,进程启动,当用户单击停止按钮时,它应该停止正在运行的进程,但是当进程启动时,控制永远不会返回到原始 GUI。 任何人都可以解决它吗? 代码片段如下:-

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(java.awt.event.ActionEvent evt) {
// TODO 在此处添加您的处理代码:

    process.destroy();    

}

【问题讨论】:

    标签: java


    【解决方案1】:

    下面一行:

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

    等待stdout 流结束。当您等待子进程stdout 结束时,您的程序将不会继续,因此您的事件循环没有运行,您将无法再按任何按钮。

    要解决此问题,您需要定期读取brCleanUp,同时仍让 GUI 事件循环运行。

    【讨论】:

      【解决方案2】:

      作为一般规则,您不希望在 Swing 事件调度线程上执行任何长时间运行的任务;你会想把你的读数从 EDT 的那个输入移开。一种可能性是使用SwingWorker

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-25
        • 2013-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-29
        相关资源
        最近更新 更多