我的工具包含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());
}
一切正常但我仍有一些问题:
答案 0 :(得分:1)
使用SwingWorker
。它提供了从EDT中删除长时间运行任务的功能,同时在EDT上更新GUI。
答案 1 :(得分:0)
在线程中运行您所拥有的内容很简单:
// 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();
答案 2 :(得分:0)
如果您不希望在执行.exe时阻止您的UI,那么只需在子线程中执行run.exec。此外,您可以将一个回调函数注册到子线程,它可以在执行结束时回调。