Distributed Listeners
Swing uses an event model that enables UI delegates to monitor their models for changes. Under this model, a UI delegate registers itself with its model as a listener. It listens for specific events, including property changes, that may require it to redraw itself. This event model, however, is sufficiently abstract to allow any object to listen for changes in a model. In fact, any object that has interesting things happen to it—a change in a value, a change in its internal structure, etc.—can allow other objects to listen for when those things occur. When one of those things occur, the object of interest notifies its listeners of the occurrence.
The example most people are familiar with is a button component. When
you place a button on a screen, your application probably wants to
know when someone clicks on the button so that an appropriate action
can be performed. A button supports ActionListener
listeners. An
ActionEvent
is an event that occurs when a user requests a GUI component to do
its thing. The user request usually comes in the form of hitting the
Enter key or clicking on the component. Using the following code, an
application can register what should happen when the button is
clicked:
JButton button = new JButton("Save"); button.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent evt) { save( ); } });
This code creates an anonymous class that listens to the button for
ActionEvent
occurrences. This example is mercifully ...
Get Database Programming with JDBC & Java, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.