![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson | Search |
List data events occur when the contents of a mutable listchange. The list's model fires these events, the list does not. So 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.
The following applet demonstrates list data events on a mutable list:
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.You can find the applet's code in
Try this:
- Type in the name of your favorite ski resort and click the Add button.
- Select a few continguous items in the list and click the Delete button.
- Select one item and move it up or down in the list with the arrow buttons.
ListDataEventDemo.java
. You will also need two image files.
Here's the code from the applet 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); } }
TheListDataListener
interface contains these three methods:Each list selection event method has a single parameter: a
void intervalAdded(ListDataEvent)
- Called when one or more items have been added to the list.
void intervalRemoved(ListDataEvent)
- Called when one or more items have been removed from the list.
void contentsChanged(ListDataEvent)
- Called when the contents of one or more items in the list have changed.
ListDataEvent
object. To get the source of a
ListDataEvent
, use thegetSource
method, whichListDataEvent
inherits fromEventObject
.
The
ListDataEvent
class defines the following handy methods:
int getIndex0()
- Returns the index of the first item whose value has changed.
int getIndex1()
- Returns the index of the last item whose value has changed.
The following table lists the examples that use list data listeners.
Example Where Described Notes ListDataEventDemo
This section Reports all list data events that occur on a list.
![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson | Search |