Representing List Data

Swing uses one interface and two classes to maintain a model of the list elements. When programming with lists, you often find that you can reuse these classes without modification. Occasionally, you may find it necessary to extend or even rewrite these classes to provide special functionality. In either case, it’s important to examine all three in detail. Let’s start with the easiest: ListModel.

The ListModel Interface

ListModel is a simple interface for accessing the data of the list. It has four methods: one method to retrieve data in the list, one method to obtain the total size of the list, and two methods to register and unregister change listeners on the list data. Note that the ListModel interface itself contains a method only for retrieving the list elements — not for setting them. Methods that set list values are defined in classes that implement this interface.

Properties

The ListModel interface defines two properties, shown in Table 7-1. elementAt is an indexed property that lets you retrieve individual objects from the list; size tells you the total number of elements.

Table 7-1. ListModel properties

Property

Data type

get

is

set

Default value

elementAt i

Object

·

   

size

int

·

   

iindexed

     

Events

The ListModel interface also contains the standard addListDataListener( ) and removeListDataListener( ) event subscription methods. These methods accept listeners that notify when the contents of the list have changed. A ListDataEvent should be generated ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.