eclipse 如何在eclipse中打印到textArea而不是控制台?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/564913/
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
How to print to textArea instead of console in eclipse?
提问by user24081
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 in a seperate class. 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 中的文本框。这可能吗,如果是的话,我将如何去做。
回答by user24081
If you really want to do this, set the System OutputStream to a PipedOutputStream and connect that to a PipedInputStream that you read from to add text to your component, for example:
如果您真的想这样做,请将 System OutputStream 设置为 PipedOutputStream 并将其连接到您从中读取以向组件添加文本的 PipedInputStream,例如:
PipedOutputStream pOut = new PipedOutputStream();
System.setOut(new PrintStream(pOut));
PipedInputStream pIn = new PipedInputStream(pOut);
BufferedReader reader = new BufferedReader(new InputStreamReader(pIn));
You can then read from the reader and write it to your text component, for example:
然后您可以从阅读器读取并将其写入您的文本组件,例如:
while(appRunning) {
try {
String line = reader.readLine();
if(line != null) {
// Write line to component
}
} catch (IOException ex) {
// Handle ex
}
}
I'd suggest that you don't use System.out for your application output though, it can be used by anything (e.g. any third party libraries you decide to use). I'd use logging of some sort (java.util.logging, Log4J etc) with an appropriate appender to write to your component.
我建议你不要将 System.out 用于你的应用程序输出,它可以被任何东西使用(例如你决定使用的任何第三方库)。我会使用某种类型的日志记录(java.util.logging、Log4J 等)和适当的附加程序来写入您的组件。