[英]How do I write logs and display them real-time in a Java Swing application?
I have created a GUI program that uses a class to perform some tasks.我创建了一个 GUI 程序,它使用 class 来执行一些任务。
I would like to add logging in both the JFrame
and the class.我想在
JFrame
和 class 中添加日志记录。 Logs should be kept in a file and displayed in a JTextArea
concurrently.日志应保存在文件中并同时显示在
JTextArea
中。
What is a convient solution for this?对此有什么方便的解决方案?
Create a wrapper that创建一个包装器
public void log(String msg) { appendToJTextArea(msg); LOG.info(msg); }
I suggest using a simple System.out.println()
call and then running your application like this:我建议使用简单的
System.out.println()
调用,然后像这样运行您的应用程序:
java -cp path/to/my/class/or/jar/MyClass.class MyClass -debug > myLog.log
Which will create a text pane for you ( -debug
parameter), as well as put them in a log file for you.这将为您创建一个文本窗格(
-debug
参数),并为您将它们放入日志文件中。
One of the ways you can log to a file easily is to use a FileWriter:您可以轻松登录到文件的一种方法是使用 FileWriter:
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileWriter.html http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileWriter.html
Additionally, as you log data you can always update the text of a JTextArea with JTextArea.append():此外,当您记录数据时,您始终可以使用 JTextArea.append() 更新 JTextArea 的文本:
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JTextArea.html http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JTextArea.html
If you're logging to a file, might I suggest logging to multiple timestamped files?如果您要登录到一个文件,我是否建议您登录到多个时间戳文件? This ensures that you're saving the data and that you won't lose too much in the event of a program crash.
这可确保您保存数据,并且在程序崩溃时不会丢失太多。
Hope this helped!希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.