
80
|
Chapter 2, Lists and Combos
#17 Reorder a JList with Drag-and-Drop
HACK
H A C K
#17
Reorder a JList with Drag-and-Drop Hack #17
Let users put things where they want.
You may be so used to immutable lists that the idea of reordering a list with
drag-and-drop seems unnatural. The first time I saw it—rearranging the
order of network devices in Mac OS X to establish a priority (e.g., try Ether-
net, then wireless, then modem)—I thought it was kind of odd. In fact,
Apple felt it necessary to put a label on the list to tell users they could drag-
and-drop the list items to rearrange them. Now that I’m used to it, it’s
totally cool, and I’d like to see it done in more places.
To implement this functionality in a
JList, you basically just have to imple-
ment the full set of AWT drag-and-drop interfaces because the list will be
both the source of the drag and the target of the drop. The other thing you
need to do is to use some cell rendering tricks to provide a visual cue as to
where the drop will occur.
The
ReorderableJList, shown in Example 2-12, is a JList that uses a
DefaultListModel, which is mutable for the obvious reason that it will
need to change in response to drag-and-drops. The bulk of it is concerned
with implementing the drag-and-drop interfaces
DragSourceListener,
DropTargetListener, and DragGestureListener. It has an inner class imple-
menting
Tranferable to hold the item being dropped, although ...