最简单的方法是定义记录器接口:
package com.example.logging;public interface ActivityLogger { void logAction(String message);}然后将其传递给您的非GUI组件,这样它们就不会与特定的实现挂钩:
public class FileLoader { private ActivityLogger logger; public FileLoader(ActivityLogger logger){ this.logger = logger; } public void loadFile(){ // load stuff from file logger.logAction("File loaded successfully"); }}现在,进行写入文本组件的实现很简单:
public class TextComponentLogger implements ActivityLogger{ private final JTextComponent target; public TextComponentLogger(JTextComponent target) { this.target = target; } public void logAction(final String message){ SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { target.setText(String.format("%s%s%n", target.getText(), message)); } }); }}// Usage:Jtextarea logView = new Jtextarea();TextComponentLogger logger = new TextComponentLogger(logView);FileLoader fileLoader = new FileLoader(logger);fileLoader.loadFile();当然,您也可以使用标准的日志记录框架(java.util.logging,slf4j,log4j等),并编写一个“写入”文本组件的附加程序。



