Check out how ActionListener, ChangeListener et all work. In short, this is the basis:
- create a subclass of java.util.EventObject or one of its sub classes:
If you extend AWTEvent you override paramString instead of toString. An example:
- create an interface that extends java.util.EventListener or one of its sub interfaces:
The name of the methods usually indicate what happened, like actionPerformed, stateChanged, treeNodesInserted.
- if there is more than one method in the listener, create an abstract implementing class that implements all methods with an empty body. By subclassing this class you can avoid having to implement all methods; just override the ones you need:
In the code that will fire the triggers you can use two basic methods.
Method 1 - use a List to store the listeners:
Method 2 - use an EventListenerList to store the listeners:
You should generally use EventListenerList if you have more than one listener type, or your super class already has it. JComponent for instance has a protected instance; you should reuse that.
The fire methods should be named fire followed by the event method name with its first character changed to uppercase. For example, fireActionPerformed, fireStateChanged, etc. The parameters should either be an event object you create elsewhere, or any parameters you need for constructing the event. If you want both, that's just fine. Overloaded versions are not a problem at all.
If you want more examples, I suggest you look in the javax.swing package; the source is available as src.zip in your JDK folder.