Search code examples
javaloggingjtextarea

Java Log ==> JTextArea


Need: Output a Java application's log into a GUI component, such as a JTextArea.

Concern: Need to log things from any class, in a static manner. However, the GUI logger component must not be static (obviously) as it's the member of a parent component.

What should I do?


Solution

  • Create a singelton log provider and add the "textfield" as a listener to it.

    Example of the logger singelton:

    interface Listener {
        void log(String log);
    }
    
    enum Logger {
    
        instance;
    
        private List<Listener> listeners = new LinkedList<Listener>();
    
        public void addListener(Listener l) {
        synchronized(listeners) {
            listeners.add(l);
         }
        }
    
        public void log(String log) {
            synchronized(listeners) {
                for(Listener l : listeners)
                    l.log(log);
            }
        }
    }
    

    Add your listener (which you will need to implement yourself) like this:

    Logger.instance.addListener(myTextField);
    

    And use it (from any class) like this:

    Logger.instance.log("Hello World!");
    

    Or you can use a package like log4j.