最も簡単な方法は、ロガー・インターフェースを定義することです:今
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");
}
}
:彼らは具体的な実装に縛られませんので、
package com.example.logging;
public interface ActivityLogger {
void logAction(String message);
}
次に、あなたの非GUIコンポーネントに渡しますテキストコンポーネントに書き込む実装は簡単です:
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など)を使用し、テキストコンポーネントに「書き込む」アペンダーを作成します。