Aside: Adding and Removing Listeners
to Composites
Some composite objects, including Swing components, have the the
ability to notify listeners of changes. Normally, Java code that uses
the text2gui library does not need to add its own listeners to
composites because user event processing is performed through argument
map property changes. Using model code to add listeners to composites
manually also violates the MVC principle since assumptions are made on
the implementation of the view/controller. However, for more
fine-grained control, sometimes adding listeners to composites is
appropriate.
Adding scripted listeners to composites via resource bundle definitions
is fairly common, and does not violate the MVC principle since the only
the view/controller knows about these listeners. We now discuss the
mechanism and rules of adding and removing listeners to composites.
For each type of listener a composite object supports, the text2gui
library treats the list of listeners as a property of the composite.
Each list of listeners is converted by an instance collection
converter, then each listener is added to the composite. As a
consequence, you can set the listeners of a composite object with code
like this (in a properties
resource bundle):
scrollpane.viewportView=%table
table.values.0.0="Beethoven"
table.values.0.1="Moonlight Sonata"
table.values.1.0="Chopin"
table.values.1.1="Etude Op 10 No 3"
table.values.2.0="Toni Braxton"
table.values.2.1="Spanish Guitar"
table.values.3.0="George Winston"
table.values.3.1="Thanksgiving"
table.columnNames.0="Composer"
table.columnNames.1="Piece"
table.listSelectionListeners.0=%soulListener
table.listSelectionListeners.1=%polishListener
# more listeners here ...
soulListener={
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() ||
!e.getSource().isSelectedIndex(2)) {
return;
}
dialog = DispatchingComponentConverter.DEFAULT_INSTANCE.
toComponent(bundle, "soulDialog", null);
dialog.pack();
dialog.show();
}
}
}
When the user selects the row containing "Toni Braxton", the list
selection listener is notified and a dialog is shown.
Updating the list of listeners is a bit trickier. You'd think that
setting the list of listeners would remove the each of the old
listeners first. However, some composite objects already have their own
listeners attached to them, to implement some of their core
functionality. Therefore it would be a mistake to unconditionally
remove all listeners from a composite object. Instead, only listeners
implementing com.taco.text.CompositeConverter.IClientListener
are
removed. This means if you want to be able to remove a listener that
you add to a composite object, the listeners must implement
IClientListener.
In practice, setting the list of listeners after conversion is
uncommon, but hopefully this document will help you if this issue ever
comes up.