gpt4 book ai didi

java - System.out.println 到 JTextArea

转载 作者:搜寻专家 更新时间:2023-11-01 01:06:30 32 4
gpt4 key购买 nike

编辑:我已经编辑了帖子以澄清我的问题,现在我自己有了更多的理解。

正如标题所说,我本质上是在尝试将控制台输出到我的 GUI 中的 JTextArea,同时执行应用程序的任务。

这是我目前正在做的事情:

public class TextAreaOutputStream extends OutputStream
{

private final JTextArea textArea;

private final StringBuilder sb = new StringBuilder();

public TextAreaOutputStream(final JTextArea textArea)
{
this.textArea = textArea;
}

@Override
public void flush()
{
}

@Override
public void close()
{
}

@Override
public void write(int b) throws IOException
{

if (b == '\r')
return;

if (b == '\n')
{
final String text = sb.toString() + "\n";
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
textArea.append(text);
}
});
sb.setLength(0);
}
sb.append((char) b);
}
}

以上将成功地将 System.out 重定向到我上面的输出流,因此将事件发送到 EventQueue 以更新我的 GUI (JTextArea)。

问题是:

目前使用 invokeLater() 将如文档中所述:

使 runnable 在 EventQueue 的调度线程中调用其运行方法。这将在处理完所有未决事件后发生。

所以我真正想做的是在处理 EventQueue 中的所有其他内容之前执行对 GUI 的更新(调用 run())。

是否可以将事件本质上注入(inject)到我的 EventQueue 中?或者有人可以给我指点一个关于这个领域的不错的教程吗?

谢谢,

最佳答案

以下示例创建带有文本区域的框架并将 System.out 重定向到它:

import java.awt.BorderLayout;
import java.awt.Container;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class JTextAreaOutputStream extends OutputStream
{
private final JTextArea destination;

public JTextAreaOutputStream (JTextArea destination)
{
if (destination == null)
throw new IllegalArgumentException ("Destination is null");

this.destination = destination;
}

@Override
public void write(byte[] buffer, int offset, int length) throws IOException
{
final String text = new String (buffer, offset, length);
SwingUtilities.invokeLater(new Runnable ()
{
@Override
public void run()
{
destination.append (text);
}
});
}

@Override
public void write(int b) throws IOException
{
write (new byte [] {(byte)b}, 0, 1);
}

public static void main (String[] args) throws Exception
{
JTextArea textArea = new JTextArea (25, 80);

textArea.setEditable (false);

JFrame frame = new JFrame ("stdout");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane ();
contentPane.setLayout (new BorderLayout ());
contentPane.add (
new JScrollPane (
textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED),
BorderLayout.CENTER);
frame.pack ();
frame.setVisible (true);

JTextAreaOutputStream out = new JTextAreaOutputStream (textArea);
System.setOut (new PrintStream (out));

while (true)
{
System.out.println ("Current time: " + System.currentTimeMillis ());
Thread.sleep (1000L);
}
}
}

关于java - System.out.println 到 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14706674/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com