【问题标题】:Printing Console to JFrame TextArea - acts weirdly (flashing screen)打印控制台到 JFrame TextArea - 行为怪异(闪烁屏幕)
【发布时间】:2020-03-09 16:09:04
【问题描述】:

我有一个项目,它在控制台中逐行打印出数字,我成功地将它重定向到我用于此应用程序的 GUI Jframe。但是,当数字打印到 TextArea 中时,它们并不会像滚动列表那样一一显示。相反,我看到整个 TextArea 一遍又一遍地闪烁和打印。阅读完成后,TextArea 中的一切看起来都是正确的。有没有办法正确设置它,让它打印得像我在控制台中看到的一样?

非常感谢您提供的任何帮助!

对于 system.out 的重定向,我有以下代码:

package ibanchecker03;

import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;

public class CustomOutputStream extends OutputStream {    
    private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea=textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char)b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getDocument().getLength());
        // keeps the textArea up to date
        textArea.update(textArea.getGraphics());
    }
}

然后在应用程序类中我有这个来重定向输出:

PrintStream printStream = new PrintStream(new CustomOutputStream(display));
System.setOut(printStream);
System.setErr(printStream);

【问题讨论】:

  • 您帖子的正文和标题大约是TextField。代码显示 JTextArea 。请edit您的帖子修复它并制作您的代码minimal reproducible example
  • 感谢您通知我,已更正。 .)

标签: java swing console system.out printstream


【解决方案1】:

我建议您实现一个缓冲区(使用StringBuilder)并附加到该缓冲区,而不是写入每个字符(并更新每个字符的textArea)。仅更新 flush() 上的 textArea 并在单独的线程中执行此操作。类似的,

public class CustomOutputStream extends OutputStream {
    private StringBuilder sb = new StringBuilder();
    private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        sb.append((char) b);
    }

    @Override
    public void flush() {
        if (sb.length() > 0) {
            final String toWrite = sb.toString();
            sb.setLength(0);
            SwingUtilities.invokeLater(() -> {
                textArea.append(toWrite);
                textArea.setCaretPosition(textArea.getDocument().getLength());
                textArea.update(textArea.getGraphics());
            });
        }
    }

    @Override
    public void close() {
        flush();
        sb = null;
    }
}

【讨论】:

  • 嗨,这看起来是一个很好的解决方法。但是,当我应用它时,我在 textArea 中看不到任何输出。一定还缺少什么。
猜你喜欢
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多