Java 如何将所有控制台输出重定向到 GUI 文本框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/564759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:17:10  来源:igfitidea点击:

How to redirect all console output to a GUI textbox?

javaeclipseuser-interface

提问by

I currently have a program that prints lines of text to the screen in various manners such as 'System.out.println()' statements and for loops the print all elements in an array to screen.

我目前有一个程序,它以各种方式将文本行打印到屏幕上,例如 'System.out.println()' 语句和 for 循环将数组中的所有元素打印到屏幕上。

I am now adding a GUI to this program. My problem is that I want to print everything that prints to eclipse's console to a textbox in my GUI instead. Is this possible and if so how would I go about doing this.

我现在正在向这个程序添加一个 GUI。我的问题是我想将打印到 eclipse 控制台的所有内容打印到我的 GUI 中的文本框。这可能吗,如果是的话,我将如何去做。

Thanks in Advance.

提前致谢。

回答by Romain Linsolas

An idea:

一个主意:

Create your own PrintStream that outputs everything to this textbox. Then set this new PrintStream to be the standard outputstream like that:

创建您自己的 PrintStream,将所有内容输出到此文本框。然后将这个新的 PrintStream 设置为标准输出流,如下所示:

System.setOut(myPrintStream());

回答by theomega

Check out this blog article, entitled Redirecting System.out and System.err to JTextPane or JTextArea. It describes almost everything you need.

查看这篇名为将 System.out 和 System.err 重定向到 JTextPane 或 JTextArea 的博客文章。它几乎描述了您需要的一切。

The basic idea is that you create your own specialized output stream. In your implementation of the write()methods, you call some code to append the new data to your text box. Then, you set this new output stream as your System.outby calling System.setOut()or System.setErr().

基本思想是您创建自己的专用输出流。在write()方法的实现中,您调用一些代码将新数据附加到文本框。然后,您System.out通过调用System.setOut()或将这个新的输出流设置为您的System.setErr()

NOTE: that article is missing one thing. You need to start your program in a separate thread.

注意:那篇文章缺少一件事。您需要在单独的线程中启动您的程序