我有一个处理某些数据的 GUI 应用程序,它将文本行转换为对象。创建的每个对象都显示在 JTextPane 或 JTextArea 上。示例:
第 1 行创建了 827401830 第 2 行创建了 827401831
所以用户被告知这个过程。
在后台,有一个线程在后台运行并完成所有工作。问题是该线程的其中一个字段是 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)?
谢谢!
最佳答案
不是传递 JTextArea
,而是传递 OutputStream
(例如 PrintStream
)作为参数。这提供了足够的灵 active :
- 你的线程只是写入输出流
- 如果您希望输出出现在
JTextArea
中,您可以传递一个输出流,它将输出附加到JTextArea
。写入文本区域应该发生在 EDT 上,但输出流会处理这个。您的线程不知道这一点 - 如果您想将输出通过管道传输到
System.out
,只需将System.out
作为参数直接传递即可
关于java - 如何从没有 swing 组件初始化的线程将数据记录到 JTextArea(或 JTextPane)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10449791/