Java Reference
In-Depth Information
To use this custom component, create it by calling the constructor,
DualListBox
sdual = new DualListBox()
, and then fill it with data by using either
setSourceElements()
or
addSourceElements()
; each takes either a
ListModel
or an array argument. The
add
version
supplements the existing choices, whereas the
set
version clears out the choices first. When it's
time to ask the component what the user selected, you can ask for an
Iterator
of the chosen
elements with
destinationIterator()
. Some properties you may want to change include
the following:
•
The source choices' title (Available Choices in the example)
•
The destination choices' title (Your Choices in the example)
•
The source or destination list cell renderer
•
The source or destination visible row count
•
The source or destination foreground color or background color
The complete source code for this new
DualListBox
component follows. Listing 13-9
contains the first class
SortedListModel
, which provides a sorted
ListModel
. Internally, this
takes advantage of a
TreeSet
.
Listing 13-9.
Sorted List Model
import javax.swing.*;
import java.util.*;
public class SortedListModel extends AbstractListModel {
SortedSet<Object> model;
public SortedListModel() {
model = new TreeSet<Object>();
}
public int getSize() {
return model.size();
}
public Object getElementAt(int index) {
return model.toArray()[index];
}
public void add(Object element) {
if (model.add(element)) {
fireContentsChanged(this, 0, getSize());
}
}