img
Method
Description
void addObser ver(Obser ver obj)
Adds obj to the list of objects obser ving the invoking object.
protected void clearChanged( )
Calling this method returns the status of the invoking object
to "unchanged."
int countObser vers( )
Returns the number of objects obser ving the invoking object.
void deleteObser ver(Obser ver obj) Removes obj from the list of objects obser ving the invoking
object.
void deleteObser vers( )
Removes all obser vers for the invoking object.
boolean hasChanged( )
Returns true if the invoking object has been modified and
false if it has not.
void notifyObser vers( )
Notifies all obser vers of the invoking object that it has
changed by calling update( ). A null is passed as the second
argument to update( ).
void notifyObser vers(Object obj)
Notifies all obser vers of the invoking object that it has
changed by calling update( ). obj is passed as an argument
to update( ).
protected void setChanged( )
Called when the invoking object has changed.
TABLE 18-7
The Methods Defined by Observable
The Obser ver Interface
To observe an observable object, you must implement the Observer interface. This interface
defines only the one method shown here:
void update(Observable observOb, Object arg)
Here, observOb is the object being observed, and arg is the value passed by notifyObservers( ).
The update( ) method is called when a change in the observed object takes place.
An Obser ver Example
Here is an example that demonstrates an observable object. It creates an observer class,
called Watcher, that implements the Observer interface. The class being monitored is called
BeingWatched. It extends Observable. Inside BeingWatched is the method counter( ),
which simply counts down from a specified value. It uses sleep( ) to wait a tenth of a
second between counts. Each time the count changes, notifyObservers( ) is called with the
current count passed as its argument. This causes the update( ) method inside Watcher to
be called, which displays the current count. Inside main( ), a Watcher and a BeingWatched
object, called observing and observed, respectively, are created. Then, observing is added
to the list of observers for observed. This means that observing.update( ) will be called each
time counter( ) calls notifyObservers( ).
/* Demonstrate the Observable class and the
Observer interface.
*/
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home