June 14, 2010, 12:15 p.m.
posted by pythonrocks
How to Write a List Data ListenerList data events occur when the contents of a mutable list change. Since the model—not the component—fires these events, you have to register a list data listener with the list model. If you haven't explicitly created a list with a mutable list model, then your list is immutable and its model will not fire these events.
Note: Combo box models also fire list data events. However, you normally don't need to know about them unless you're creating a custom combo box model. Figure demonstrates list data events on a mutable list: Figure. The ListDataEventDemo application.
Try This:
You can find the demo's code in ListDataEventDemo.java. Here's the code that registers a list data listener on the list model and implements the listener:
//...where member variables are declared...
private DefaultListModel listModel;
...
//Create and populate the list model
listModel = new DefaultListModel();
...
listModel.addListDataListener(new MyListDataListener());
class MyListDataListener implements ListDataListener {
public void contentsChanged(ListDataEvent e) {
log.append("contentsChanged: " + e.getIndex0() +
", " + e.getIndex1() + newline);
}
public void intervalAdded(ListDataEvent e) {
log.append("intervalAdded: " + e.getIndex0() +
", " + e.getIndex1() + newline);
}
public void intervalRemoved(ListDataEvent e) {
log.append("intervalRemoved: " + e.getIndex0() +
", " + e.getIndex1() + newline);
}
}
The List Data Listener APIFigure lists the methods in the ListDataListener interface and Figure describes the methods in the ListDataEvent class. Note that ListDataListener has no corresponding adapter class. Also refer to the ListDataListener API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/ListDataListener.html. The API documentation for ListDataEvent is online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/ListDataEvent.html.
Examples That Use List Data ListenersThe following examples use list data listeners.
|
- Comment
