嗨,我是 Java 编程新手。我正在尝试从 Java 执行外部命令,然后在 JTextArea 中显示命令提示符输出in real time
。该外部程序将每秒生成 1 行输出,然后在 10 秒后退出。
以下是我的 Java 代码:
original codes have been deleted to save space after reading Kumra's answer
当我在命令提示符窗口中手动运行 program.exe 时,输出会实时更新,如下所示:
<some warning message of the .exe program
which should not affect the output of the program> // shown at t=0
output line 1 //shown at t=1
output line 2 //shown at t=2
output line 3 //shown at t=3
output line 4 //shown at t=4
output line 5 //shown at t=5
output line 6 //shown at t=6
output line 7 //shown at t=7
output line 8 //shown at t=8
output line 9 //shown at t=9
output line 10 //shown at t=10
Done. //shown at t=10.
当我在上面运行我的 Java 程序时,我认为 JTextArea 将实时更新以显示命令提示符输出。不幸的是,它不起作用。实际输出是这样的:
<some warning message of the .exe program
which should not affect the output of the program> // shown at t=0
从 t=0 到 t=10,JTextArea 卡在上面的输出中。在 t=11 时,它突然显示完整的输出:
<some warning message of the .exe program
which should not affect the output of the program> // shown at t=0
output line 1 //shown at t=11
output line 2 //shown at t=11
output line 3 //shown at t=11
output line 4 //shown at t=11
output line 5 //shown at t=11
output line 6 //shown at t=11
output line 7 //shown at t=11
output line 8 //shown at t=11
output line 9 //shown at t=11
output line 10 //shown at t=11
Done. //shown at t=11
我可以知道我的代码有什么问题吗?谁能教我如何在 JTextArea 中显示命令提示符输出in real time
?谢谢。
编辑 1:
我已经根据 Kumar 的回答编辑了代码,但它仍然无法正常工作。下面是最新的代码。
MyUI.java
public class MyUI extends JFrame
implements ActionListener, KeyListener, ChangeListener, WindowListener
{
...
private JTextArea output;
public void showMessage(String message)
{
output.append(message + "\n");
output.setCaretPosition(output.getDocument().getLength());
}
...
public void actionPerformed(final ActionEvent e)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if (xxxxx)
{
myThreadInstance = new MyThread(xx,xxx,xx,xx,xx);
myThreadInstance.start();
}
}
}
}
}
MyThread.java
public class MyThread extends Thread
{
...
public MyUI myFrame;
...
public void run
{
try
{
String command = "program.exe arg1 arg2 arg3 arg4";
List<String> items = Arrays.asList(command.split("\\s+"));
builder = new ProcessBuilder(items);
builder.redirectErrorStream(true);
process = builder.start();
input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String inputline = null;
while ((inputline = input.readLine()) != null)
{
myFrame.showMessage(inputline);
}
}
catch(){}
finally{}
}
}