In the 1950s, Walt Disney set up a room full of moustraps
and on each were balanced two ping pong balls. He tossed a ball into the room and a
fission explosion ensued, with each ball triggering another pair of balls to fly into
the air.
This is simpilar to what happens if you are not careful about Events triggering other Events in
Java.
Sometimes, in your ChangeListener you change the
value of the component that caused the event. This in turn triggers yet another
ChangeEvent. Your app goes into an endless loop
fibrillation. You will also get into this problem with
Applet instances intercommunicating changes on a page.
- One way to avoid this problem is never to set a Component’s value programmatically without first checking if
you really need to. Don’t set unless the value has actually changed.
Components don’t do this for themselves. Any set
is treated as a change even if you are setting to the same value. You still get
unwanted ChangeEvents, but they don’t
propagate.
- The problem is more difficult to nail than you might first think. Events can
sit in queue delayed for a while, which can often defeat simple boolean variable schemes.
- A reasonably robust scheme is to have the listener check to see if anything has
really changed and, if not, just return, without propagating the change trigger on
in any way.
- You also have to be careful with any sort of toggle. If you expect an event to
turn the toggle on or off, that event might arrive too early, too late, or get lost
altogether. I have found that different browsers and different
JVMs (Java Virtual Machines)
seem to behave slightly differently in this regard.
- JCheckBox.setSelectedItem
will trigger an ActionEvent that is immediately
dispatched, even before your event handler completes. This is almost never what you
want. You usually need to create some mechanism to ignore the event. Otherwise you
can get a fibrillation where events trigger more events in an uncontrolled
way.
I have put in an RFE (Request For Enhancement) to Sun asking them to
provide ways to set components while temporarily inhibiting the triggering of new
change events.
Redirect Fibrillation
A somewhat slower, but equally irritating fibrillation occurs when a website
issues an HTTP (Hypertext Transfer Protocol) 303 permanent redirect
from URL (Uniform Resource Locator) A to B and simultaneously one from B to A. If you
correct your website links daily, each day to must toggle between A and B. Even more
pathological is a single redirect chain that goes in an endless loop.