gpt4 book ai didi

java - 如何将控制台内容重定向到 Java 中的文本区域?

转载 作者:行者123 更新时间:2023-12-01 16:32:09 25 4
gpt4 key购买 nike

我正在尝试在java中的textArea中获取控制台的内容。

例如,如果我们有这段代码,

class FirstApp {
public static void main (String[] args){
System.out.println("Hello World");
}
}

我想将“Hello World”输出到文本区域,我必须选择什么actionPerformed?

最佳答案

我找到了这个简单的解决方案:

首先,您必须创建一个类来替换标准输出:

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());
}
}

然后按如下方式替换标准:

JTextArea textArea = new JTextArea(50, 10);
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea));
System.setOut(printStream);
System.setErr(printStream);

问题是所有输出都只会显示在文本区域中。

示例来源:http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea

关于java - 如何将控制台内容重定向到 Java 中的文本区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62019811/

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