我一直在尝试使用自定义输出流来显示 Jtext 区域上可执行文件的输出。
通过按钮调用可执行文件
try {
Process p = Runtime.getRuntime().exec("cgminer.exe" + " -o " + Infos.Address + ":" + Infos.Port + " -u " + Infos.User + " -p " + Infos.Password);
p.waitFor();
String line;
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while((line = error.readLine()) != null){
System.out.println(line);
}
error.close();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line=input.readLine()) != null){
System.out.println(line);
}
input.close();
OutputStream outputStream = p.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.println();
printStream.flush();
printStream.close();
}
catch (Exception e) {
// ...
}
}
}
然后将输出定向到带有
的jtextpublic class CustomOutputStream extends OutputStream {
private JTextArea textArea;
public CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}
@Override
public void write(int b) throws IOException {
textArea.append(String.valueOf((char) b));
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
我的问题是当我调用第一个类时按钮锁定并且没有输出到 jtext。只有当我强制关闭 cgminer 时才会出现输出。
非常感谢任何帮助,因为这让我的大脑扭曲了。
最佳答案
My problem is when I call the first class the button locks and no output makes it to the jtext. It is only when I force close the cgminer that the output appears.
这是阻塞 Swing 事件线程的典型症状。当您在 Swing 事件线程(也称为 EDT 或 Event Dispatch Thread),你阻止线程做它的杂务,包括绘制 GUI 和与用户交互,有效地“卡住”GUI。
解决方案不是像另一个建议那样注释 waitFor()
,而是在后台线程(例如 SwingWorker)中运行它和任何其他阻塞代码。当您执行此操作时,请确保只在事件线程上更新您的 Swing GUI。 SwingWorker 具有通过其发布和处理方法执行此操作的内置方法。
详情请查看Concurrency in Swing
您还需要执行更多线程,因为您的某些代码行正在阻塞,并且会阻止下游行运行,直到它们解除阻塞,但到那时所有重要的操作都已完成。例如这些 block :
// this blocks
p.waitFor();
// this blocks both times you use it
while((line = error.readLine()) != null){
System.out.println(line);
}
关于JAVA - 从启动器调用时外部 exe 锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18198537/