Consider a structure of JPanels as follows:
MainPanel contains two panels: AdminPanel and ReportPanel.
AdminPanel contains SetupPanel, which contains LogoPanel.
I would like to notify ReportPanel about certain changes in LogoPanel.
To do this, I have implemented a property-change listener in ReportsPanel. I also have in ReportsPanel a static reference to itself.
LogoPanel uses this static reference to call the listener.
This solution works, but does not seem elegant to me.
My question: is there a more elegant way to do it ?
The solution I crafted goes as follows:
Created a simple interface:
public interface Follower {
public void changed(String property);
}
and a listener class :
public class LogoListener {
/**
* A static reference to this.
*/
private static LogoListener listener;
/**
* Represents the objects to be notified by the listener.
*/
private static List<Follower> followers;
/**
* Create a simple listener to be used by one "notifying"
* object, and "followers" objects.
*
*/
private LogoListener() {
followers = new ArrayList<Follower>();
listener = this;
}
/**
* Method to be used by the "notifying" object, to
* notify followers.
*/
public void notifyFollowers() {
for(Follower follower : followers){
follower.changed("Logo changed");
}
System.out.println("Logo changed");
}
/**
* Get the listener instance, or create one if it does not exist.
*
* @return the listener
*
*/
public static LogoListener getListener() {
if(listener == null) {
listener = new LogoListener();
}
return listener;
}
/**
*
* @param follower
* <br>Not null.
* @throws
* <br>IllegalArgumentException if <code>follower</code> is null.
*/
public void addFollower(Follower follower) {
if(follower == null ) {
throw new
IllegalArgumentException("Follower should not be null");
}
followers.add(follower);
}
}
Reports panel (the "follower" or listening object) implements Follower interface, which simply means override changed(String message) method:
/* (non-Javadoc)
* @see listener.Follower#changed(java.lang.String)
*/
@Override
public void changed(String msg ) {
//respond to change goes here
System.out.println(msg);
}
and register as a follower by :
LogoListener.getListener()
.addFollower(this);
Logo panel notifies a change by:
LogoListener listener = LogoListener.getListener();
listener.notifyFollowers();
Commnets and feedback is most welcome.