Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a JTextArea always visible in my main app window (a Log if you like), and I want to use it to display activity going on in the system (like mock-debug output you'd do with System.out.println() in if conditions or whatever)

I mean high level things the user does, (like "successfully loaded file " or " written to disk", " completed" etc)

Thing is such messages can be generated anywhere in my system mainly in another package the classes of which deal with the data and computation, and they're unaware of the GUI.

Maybe save the messages to a temp file and the textarea "monitors" that file for changes, how can this be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
280 views
Welcome To Ask or Share your Answers For Others

1 Answer

The simplest way is to define a logger interface:

package com.example.logging;
public interface ActivityLogger {
    void logAction(String message);
}

Then pass it to your non-GUI components so they don't get tied to a specific implementation:

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");
    }

}

Now, making an implementation that writes to a text component is simple:

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();

You can of course also use a standard logging framework (java.util.logging, slf4j, log4j, etc) and write an appender that "writes" to a text component.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...