您好我是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{}
}
}
答案 0 :(得分:2)
试试这个......
SwingWorker
Swing以同步UI和非UI线程。