The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples]

e334. Implementing a Simple Event Notifier

The Observer and Observable classes are superseded by a more elaborate event framework (see e333 Creating a Custom Event). However, these two classes can still be useful for implementing a simple event notifier.
    // Declare the model
    class MyModel extends Observable {
        // The setChanged() protected method must overridden to make it public
        public synchronized void setChanged() {
            super.setChanged();
        }
    }
    // Create the model
    MyModel model = new MyModel();
    
    // Register for events
    model.addObserver(new Observer() {
        public void update(Observable o, Object arg) {
        }
    });
    
    // Indicate that the model has changed
    model.setChanged();
    
    // Fire an event to all the views
    Object arg = "some information about the event";
    model.notifyObservers(arg);

 Related Examples
e331. Generating a Random Number
e332. Breaking a String into Words
e333. Creating a Custom Event
e335. Listing All Available Locales
e336. Setting the Default Locale
e337. Associating a Value with an Object

See also: Arrays    Bits    Collections    Dates    Hash Tables    Lists    Property Files    Sets    Sorted Collections    Time    Timers   


© 2002 Addison-Wesley.