开发者

java- how to stop process on button clicking

I am trying to create GUI with Start and Stop Process Button. On Clicking start button a process is started and when user clicks on stop button it should stop the running process but when process started control never return back to original GUI. Can anybody have solution for it? Code Snippet is as follows:-

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

}

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

    process.destroy();    

}


The following line:

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

waits for the end of the stdout stream. Your program will not proceed while you are waiting for the end of the subprocess stdout, so your event loop is not running and you won't be able t press any more buttons.

To fix this, you will need to read from brCleanUp periodically while still letting the GUI event loop run.


As a general rule, you don't want to do any long-running tasks on the Swing event dispatch thread; you'll want to move your reading from that input off of the EDT. One possibility would be to use a SwingWorker

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜