文档

Java™ 教程-Java Tutorials 中文版
设置丢弃模式
Trail: Creating a GUI With JFC/Swing
Lesson: Drag and Drop and Data Transfer

设置丢弃模式

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 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:

DropLocation Methods for JList, JTree, JTable and JTextComponent
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.


Previous page: TransferSupport Class
Next page: Demo - DropDemo