一部のデータを処理する GUI アプリケーションがあり、テキスト行をオブジェクトに変換します。作成された各オブジェクトは、JTextPane または JTextArea に表示されます。例:
行 # 1 が作成されました 827401830 行 # 2 が作成されました 827401831
したがって、ユーザーはプロセスを通知されます。
舞台裏では、バックグラウンドで実行され、すべての作業を行うスレッドがあります。問題は、このスレッドのフィールドの 1 つに JTextArea があることです。次のようになります。
public class ConsumerThread implements Runnable
{
private ArrayBlockingQueue<TicketExchangeLine> queue;
private JTextArea textArea;
public ExchConsumerThread(ArrayBlockingQueue<TicketExchangeLine> queue, JTextArea textArea)
{
this.queue = queue;
this.textArea = textArea;
}
public void run()
{
try
{
while (true)
{
// check if end of file from producer POV
if (queue.peek()!=null && ...)
break;
MyObject obj = queue.take();
try{
//do the process here
textArea.append("here comes the output for the user..."+obj.getID);
}catch(Exception nfe)
{
//Oops
}
}
textArea.append("\nDone!");
}catch (InterruptedException e)
{
// Oops
}catch(Exception exp)
{
exp.printStackTrace();
}
}
}
したがって、上記のコードは正常に機能し、ジョブを実行しますが、GUI からではなくこのスレッドを使用していて、理由もなく JTextArea をインスタンス化していることがあります。さらに悪いことに、プロセスを確認するためにすべてを system.out する必要があります。
質問: スレッドで Swing コンポーネントを使用せずに、すべての「処理されたデータ」を JTextArea (または場合によっては JTextPane) に記録するにはどうすればよいですか?
ありがとう!