Code
Logger logger = Logger.getLogger(TextAreaLogger.TEST.getClass().getName());
logger.setUseParentHandlers(false);
OutputStream os = new TextAreaOutputStream(new JTextArea());
logger.addHandler(new TextAreaHandler(os));
logger.info("test, TEST");
//...
class TextAreaHandler extends StreamHandler {
private void configure() {
setFormatter(new SimpleFormatter());
try {
setEncoding("UTF-8");
} catch (IOException ex) {
try {
setEncoding(null);
} catch (IOException ex2) {
// doing a setEncoding with null should always work.
// assert false;
ex2.printStackTrace();
}
}
}
public TextAreaHandler(OutputStream os) {
super();
configure();
setOutputStream(os);
}
//@see java/util/logging/ConsoleHandler.java
@Override public void publish(LogRecord record) {
super.publish(record);
flush();
}
@Override public void close() {
flush();
}
}
References
I am new with this topic and I need help, I have a class with several methods that contain logs, I want to print those logs in a JTextArea while the program is running.
ReplyDeleteSorry, I missed your comment. It may be too late, and furthermore I may not have understood the intent of your question correctly, but the "javaagent" option may be helpful.
Deletehttps://ateraimemo.com/data/swing/loggeragent.zip
> "%JAVA_HOME%\bin\java" -javaagent:loggeragent.jar -jar example.jar
public class DebugLoggerAgent {
public static void premain(String args) throws Exception {
EventQueue.invokeLater(() -> {
JTextArea textArea = new JTextArea(10, 20);
textArea.setEditable(false);
try {
OutputStream os = new TextAreaOutputStream(textArea);
PrintStream ps = new PrintStream(os, true, "UTF-8");
System.setOut(ps);
System.setErr(ps);
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("test");
JFrame frame = new JFrame("JTextArea Logger");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(textArea));
frame.pack();
frame.setVisible(true);
});
}
}