Setting the Drop Mode
When enabling drop on a component, such as a list, you need to decide how you want the drop location to be interpreted. For example, do you want to restrict the user to replacing existing entries? Do you want to only allow adding or inserting new entries? Do you want to allow both? To configure this behavior, the JList
class provides the setDropMode
method which supports the following drop modes.
- The default drop mode for
JList
isDropMode.USE_SELECTION
. When dragging in this mode, the selected item in the list moves to echo the potential drop point. On a drop the selected item shifts to the drop location. This mode is provided for backwards compatibility but is otherwise not recommended. - In
DropMode.ON
, the selected item in the list moves to echo the potential drop point, but the selected item is not affected on the drop. This mode can be used to drop on top of existing list items. - In
DropMode.INSERT
, the user is restricted to selecting the space between existing list items, or before the first item or after the last item in the list. Selecting existing list items is not allowed. DropMode.ON_OR_INSERT
is a combination of theON
andINSERT
modes.
The JTree
class provides the same set of drop modes and the JTable
class has several more specific to adding rows or columns.
To obtain the location of the drop, the TransferSupport
class provides the getDropLocation
method that returns the precise point where the drop has occurred. But for a list component, the index of the drop is more useful than a pixel location, so JList
provides a special subclass, called JList.DropLocation
. This class provides the getIndex
and isInsert
methods, which handle the math for you.
The table, tree, and text components each provide an implementation of DropLocation
with methods that make the most sense for each component. The JTable.setDropMode
method has the most choices. The following table shows the methods for all four classes:
JList.DropLocation |
JTree.DropLocation |
JTable.DropLocation |
JTextComponent.DropLocation |
---|---|---|---|
isInsert |
getChildIndex |
isInsertRow |
getIndex |
getIndex |
getPath |
isInsertColumn |
getBias |
getRow |
|||
getColumn |
Next is a demo that implements a custom transfer handler for a list component so that it fully participates in drag and drop.