我目前正在尝试将Log4J登录到JTextPane中。我想使用TextPane,因为我需要基本的高亮显示(例如,错误是红色的,信息是绿色的)。
我设置了两个记录器,一个(根记录器)将所有内容记录到一个文件中,另一个(guiLogger)只记录JTextPane中GUI上的一些错误和信息。
我目前面临的问题是,我无法附加到TextPane来工作。我目前的情况如下:
public class Log extends AppenderSkeleton{
private final JTextPane log;
private final StyledDocument doc;
public Log(){
super();
log = new JTextPane();
doc = log.getStyledDocument();
}
@Override
protected void append(LoggingEvent loggingEvent) {
try {
doc.insertString(doc.getLength(), "Hello World!", null);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
public JTextPane getView(){
return log;
}
}Log4J配置文件如下所示:
# The root-logger should log everything.
log4j.rootLogger = DEBUG, file
# Append the logs to a file.
log4j.appender.file = org.apache.log4j.RollingFileAppender
# [...]
# The logger which logs on the GUI (just some user-information).
log4j.logger.guiLogger = INFO, gui
# Append the logs to the GUI
log4j.appender.gui = mypackage.Log
# Formatting of the output:
log4j.appender.gui.layout = org.apache.log4j.PatternLayout
log4j.appender.gui.layout.ConversionPattern = %m%nappend()-method被调用,insertString()-method执行干净(它不进入catch-block),但我没有在GUI上看到TextPane中的任何内容。
我试图解决的问题是:
使用SwingUtilities.invokeLater()
insertString()-method --使用全局StyledDocument-object从JTextPane
validate()、revalidate()和repaint()等SwingWorker
insertString()-method:log.getStyledDocument().insertString(0, "Hello World!", info_log);
setText()- JTextPane的方法(仅在constructor).中工作)
由于JTextPane没有fireContentChanged()-method (或类似的),我在这里有点迷失了。
我玩得更多了,还发现了一些其他的东西:
StyledDocument被更新(调用getText()显示文本已被getText()--直接从编译器调用append()或insertString()-method )(在初始化StyledDocument和JTextPane之后),一切正常。F 246
此外,通过将该线程添加到append()-method主体中,检查了哪个线程调用了该方法:
System.out.println("Thread: "+Thread.currentThread().getName());如果我只从代码中的某个地方执行两个日志语句,它将显示如下:
Thread: AWT-EventQueue-0
Thread: AWT-EventQueue-0当我直接从append()-class的构造函数(加上上面的两个日志语句)调用Log-class时,它显示了以下内容:
Thread: AWT-EventQueue-0
Thread: AWT-EventQueue-0
Thread: AWT-EventQueue-0第一个调用可能会追加文本。但另外两个人却没办法工作。
我的图形用户界面是从AWT-EventQueue通过使用SwingUtilities.invokeLater()构建的。这两个日志调用是在相同的上下文中进行的(因此也来自EventQueue )。
发布于 2011-12-17 18:54:10
文本窗格是对附录私有的,而且您没有任何获取器。因此,我猜想GUI有一个文本窗格,记录器有另一个附加的文本窗格。
否则,您将从不与Log4j实例化的Log实例相同的Log实例中获取文本窗格。
另外,可能有几个线程使用这个附录,但是Swing组件只能从事件分派线程中访问。每个附加到文本窗格的内容都应该在一个SwingUtilities.invokeLater()调用中完成。
发布于 2011-12-18 05:49:36
检查yu是否调用setText()或setContentType(),并且可能是重新创建文档的更多方法。不要保存对文档的引用,而是从窗格中获取它。不
doc.insertString(doc.getLength(), "Hello World!", null);但
log.getStyledDocument().insertString(doc.getLength(), "Hello World!", null);https://stackoverflow.com/questions/8546995
复制相似问题