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, theJListclass provides thesetDropModemethod which supports the following drop modes.
- The default drop mode for
JListisDropMode.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_INSERTis a combination of theONandINSERTmodes.The
JTreeclass provides the same set of drop modes and theJTableclass has several more specific to adding rows or columns.To obtain the location of the drop, the
TransferSupportclass provides thegetDropLocationmethod 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, soJListprovides a special subclass, calledJList.DropLocation. This class provides thegetIndexandisInsertmethods, which handle the math for you.The table, tree, and text components each provide an implementation of
DropLocationwith methods that make the most sense for each component. TheJTable.setDropModemethod has the most choices. The following table shows the methods for all four classes:
DropLocation Methods for JList, JTree, JTable and JTextComponent JList.DropLocationJTree.DropLocationJTable.DropLocationJTextComponent.DropLocationisInsertgetChildIndexisInsertRowgetIndexgetIndexgetPathisInsertColumngetBiasgetRowgetColumnNext is a demo that implements a custom transfer handler for a list component so that it fully participates in drag and drop.