Java Reference
In-Depth Information
To prevent clutter, we omitted the java.util.Map interface from the diagram in Figure 7-2 . The java.util.Map
interface is the other super interface of ObservableMap . The following methods on the ObservableMap interface allow
you to register and unregister MapChangeListeners :
addListener(MapChangeListener<? super K, ? super V> listener)
addListener(MapChangeListener<? super K, ? super V> listener)
There are no additional convenience methods on ObservableMap .
The MapChangeListener interface has only one method: onChange(MapChangeListener.Change<? extends K, ?
extends V> change) . This method is called back when the content of the ObservableMap is manipulated. Notice that
this method's parameter type is the nested class Change that is declared in the MapChangeListener interface. Unlike
the ListChangeListener.Change class, the MapChangeListener.Change class is geared toward reporting the change
of a single key in a map. If a method call on ObservableMap affects multiple keys, as many map change events as
the number of affected keys will be fired.
The MapChangeListener.Change class provides the following methods for you to inspect the changes made to a key.
boolean wasAdded() returns true if a new value was added for the key.
boolean wasRemoved() returns true if an old value was removed from the key.
K getKey() returns the affected key.
V getValueAdded() returns the value that was added for the key.
V getValueRemoved() returns the value that was removed for the key. (Note that a put() call
with an existing key will cause the old value to be removed.)
ObservableMap<K, V> getMap()
In the example in Listing 7-3, we perform various map manipulations after attaching a MapChangeListener to
an ObservableMap . The implementation of MapChangeListener , called MyListener , includes a pretty printer for the
MapChangeListener.Change object, and prints out the map change event object when an event is fired.
Listing 7-3. MapChangeEventExample.java
import javafx.collections.FXCollections;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapChangeEventExample {
public static void main(String[] args) {
ObservableMap<String, Integer> map = FXCollections.observableHashMap();
map.addListener(new MyListener());
System.out.println("Calling put(\"First\", 1): ");
map.put("First", 1);
System.out.println("Calling put(\"First\", 100): ");
map.put("First", 100);
 
Search WWH ::




Custom Search