GUI在执行进程时无法更新(SwingUtilities.invokeLater)

时间:2011-04-01 11:56:04

标签: java process runtime.exec swingutilities

参考我在Unable to perform any action before Process.Runtime.exec statement line的上一个问题,我已将我的代码改为两部分,一个线程类CmdExec,其中包含执行外部程序的所有代码,如下所示:

    public class CmdExec extends Thread
     {
     private String cmd;
     private File path;

      public CmdExec() {
      }

      public CmdExec(String cmd, File path) {
      this.cmd = cmd;
      this.path = path;
      }

      public void run(){

  try
    {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(cmd , null, path);
        InputStream stderr = proc.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stderr);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        System.out.println("<ERROR>");
        while ( (line = br.readLine()) != null)
            System.out.println(line);
        System.out.println("</ERROR>");
        int exitVal = proc.waitFor();
        System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
      {
        t.printStackTrace();
      }

并且通过参考jtahlborn回答,我已经为GUI更新目的做了另一个Runnable类,如下所示:

       Runnable doWorkRunnable = new Runnable() {
        public void run() {
System.out.println("hello world");
btnTranscribe.setEnabled(false);
areaOutput.setEditable(false);
areaOutput.setEnabled(false);
areaOutput.setText("Performing segmentation, please wait till process is done\n"); }
        };

我调用SwingUtilities.invokeLater在实际运行process.exec()之前更改GUI以调用外部程序,如下所示:

    SwingUtilities.invokeLater(doWorkRunnable);
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd , null, path);

但是使用上面的所有代码,GUI仍然无法更新,只有在完成此过程后才会更新。我在协调这两个runnable和线程的任何特定步骤上都错了吗?

提前感谢您的大力帮助和回答

P / S:我在GUI中按下按钮时开始执行CmdExec(),如下所示:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
     strSegment = "java -Xmx2024m -jar ./LIUM_SpkDiarization-4.2.jar / --fInputMask=" +               strAudioOut + "/%s.wav"
            + " --sOutputMask=" + strCtlOut + "/%s.ctl --sOutputFormat=ctl --            doCEClustering --cMinimumOfCluster=1 new3_20110331103858";

    CmdExec tryDemo = new CmdExec();
    tryDemo = new CmdExec(strSegment, fSegment);
    tryDemo.run();

    strExtract = "./sphinx_fe -i " + strAudioOut + "/new3_20110331103858.wav"
           + " -o " + strFeatureOut + "/new3_20110331103858.mfc";
    //System.out.println (strExtract);
    //executeCommand (strExtract, fExtract);

    tryDemo = new CmdExec(strExtract, fExtract);
    tryDemo.run();
      }

1 个答案:

答案 0 :(得分:0)

你需要调用tryDemo.start(),而不是tryDemo.run()。您正在直接运行该线程,而不是产生单独的调用。