【发布时间】:2013-03-07 22:15:12
【问题描述】:
我正在通过 runtime.exec 运行一个命令,这需要一些时间。我想在此期间更新我的 ProgressBar。
我已经得到了我想要的系统输出,问题是:当进程完成时,我立刻得到了它。而不是一步步更新我的ProgressBar ...
这是一些代码
public Runtime rt = Runtime.getRuntime();
public Process pp;
public doit() {
try {
pp = rt.exec(a_long_timed_process);
InputStream is = pp.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("In:")) {
int a = line.indexOf("In:"); //get a string
int b = line.lastIndexOf("%"); //between
String lineout = line.substring(a + 3, b);//"0.00" and "99.99"
double nr = Double.parseDouble(lineout); //make it a double
int round = (int) nr; //make it a usable int
System.out.println(round);
myProgressBar.setValue(round); //UPDATE Progressbar
}
}
pp.waitFor();
} catch (IOException ex) {
Logger.getLogger(Sox.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(Sox.class.getName()).log(Level.SEVERE, null, ex);
}
}
感谢所有帮助
提前致谢
【问题讨论】:
-
不要阻塞 EDT(事件调度线程)——当这种情况发生时,GUI 将“冻结”。而不是调用
Thread.sleep(n)实现一个SwingTimer用于重复任务或SwingWorker用于长时间运行的任务。有关详细信息,请参阅Concurrency in Swing。
标签: java swing concurrency event-dispatch-thread jprogressbar