【问题标题】:Launch execution .exe from my Java tools从我的 Java 工具启动执行 .exe
【发布时间】:2011-10-29 23:21:06
【问题描述】:

我的工具带有 Java 用户界面。如果我单击一个按钮,我想启动一个应用程序。 exe 在我的工具中,我有一个控制台,我想在其中带来 .exe 的输出(控制台)。为此,我已经这样做了:

Runtime run = Runtime.getRuntime();
    StyledDocument doc = txtResult.getStyledDocument();
    SimpleAttributeSet keyWord = new SimpleAttributeSet();
    StyleConstants.setForeground(keyWord, Color.RED);

try {

    Process pp=run.exec(PATHEXE);

    BufferedReader in =new BufferedReader(new InputStreamReader(pp.getInputStream()));
    BufferedReader inErr =new BufferedReader(new InputStreamReader(pp.getErrorStream()));
    String line = null;
    String lineErr = null;
    while (((line = in.readLine()) != null) ||(lineErr = inErr.readLine()) != null) {
        if(line != null)
             doc.insertString(doc.getLength(), line+"\n", null );
        if(lineErr != null)
              doc.insertString(doc.getLength(), lineErr+"\n", keyWord );
    }

    int exitVal = pp.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    btRun.setEnabled(true);
}   catch (Exception e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
}

一切正常,但我仍然有一些问题:

  1. 我想移动执行。 exe在另一个线程上 在 .exe 执行期间释放用户界面。
  2. 在我的工具中读取输出 .exe 只是在结束时...然后运行更新我在运行时得到输出?

【问题讨论】:

    标签: java multithreading user-interface netbeans exe


    【解决方案1】:

    使用SwingWorker。它提供了从 EDT 中删除长时间运行的任务的工具,同时更新 EDT 上的 GUI。

    【讨论】:

      【解决方案2】:

      在线程中运行你所拥有的很容易:

      // put up a progress dialog or something here
      
      Runnable backgroundJob = new Runnable() {
          public void run() {
              final String output = executeJob();  // call your code you provided
              SwingUtilities.invokeLater( new Runnable() {
                  public void run() {
                      // safely do your updates to the UI here on the Swing Thread
                      // hide progress dialog here
                      updateUI( output );
                  }
              });
          }
      };
      Thread backgroundThread = new Thread( backgroundJob );
      backgroundThread.start();
      

      【讨论】:

        【解决方案3】:

        如果您不希望您的 UI 在 .exe 执行时被阻塞,那么只需在子线程中执行 run.exec。此外,您可以向子线程注册一个回调函数,它可以在执行结束时回调。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-08-26
          • 1970-01-01
          • 2020-12-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多