简体   繁体   中英

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.

I would like to add logging in both the JFrame and the class. Logs should be kept in a file and displayed in a JTextArea concurrently.

What is a convient solution for this?

Create a wrapper that

  1. updates your JTextArea
  2. logs via log4j , SLF4J or Apache Commons Logging or another logging framework
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:

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.

One of the ways you can log to a file easily is to use a FileWriter:
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():
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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM