经过长时间的搜索后,我的第一篇文章仍在这里,但仍获得有关此问题的解答,请帮助我解决此问题。
我正在使用Netbean 6.9.1来构建Java应用程序,该应用程序大量调用了几个不同的外部程序,因此我使用了进程和运行时函数来调用外部程序。
整个应用程序过程分为几个阶段,我希望通过更新GUI文本区域来通知用户应用程序当前正在运行的哪个阶段,代码如下所示:
公共无效executeCommand(字符串cmd,文件路径)
{
try
{
****areaOutput.setText("Executing audio decoding, please wait till process is done\n");****
btnTranscribe.setEnabled(false);
areaOutput.setEditable(false);
areaOutput.setEnabled(false);
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);
areaOutput.append("\n\nConversion is done, processing with features extraction....");
} catch (Throwable t)
{
t.printStackTrace();
}
}
如上面的代码所示,我希望在执行命令之前设置Textarea并禁用一些按钮,但是当应用程序运行时,所有这些行似乎都无法工作,并且在命令执行完成之前,应用程序本身没有任何更改,在运行.exec()之前先执行运行预命令代码的任何解决方案?
感谢您在此问题上的大力帮助和建议。
最好的祝福,
斯特里奇
P / S:
嗨,我为此CmdExec制作了一个Thread类,以便在其他线程中执行cmd:
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();
}
}
}
为了打电话给这个班,
CmdExec tryDemo =新的CmdExec();
tryDemo =新的CmdExec(strSegment,fSegment);
tryDemo.run();
用于启动线程,但我未能将SwingUtilities.invokeLater放在这些过程的任何部分中,它根本不会运行tryDemo.run(),因为它是无效的...
另外,我可以知道到目前为止我做得对吗?非常感谢您对这个问题的帮助
P / S 2:我刚刚为GUI更新命令添加了另一个可运行的代码(因此,用于执行进程的线程,可运行到GUI更新的线程)如下:
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"); }
};
并且我在执行过程之前使用了SwingUtilies.invokeLater,如下所示:
SwingUtilities.invokeLater(doWorkRunnable);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd , null, path);
但是所有这些都失败了,我是否为GUI和进程线程协调获得了错误的顺序?
最佳答案
您正在EDT(更新gui的线程)上执行此工作。因此,GUI不能更新,直到所有这些工作完成。您想要做的是运行一个单独的线程来完成所有工作,并定期调用状态更新的SwingUtilities.invokeLater。