こんにちは、私は 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{}
}
}