The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
Sometimes you have a complex component and you want the user to be able to drop on some parts of it, but not on others. Perhaps it is a table that allows data to be dropped only in certain columns; or perhaps it is a tree that allows data to be dropped only on certain nodes. Obviously you want the cursor to provide accurate feedback — it should only show the drop location when it is over the specific part of the component that accepts drops.
This is simple to accomplish by installing the necessary logic in the canImport(TransferHandler.TransferSupport
) method of the TransferHandler
class. It works only with this particular version of canImport
because it is called continuously while the drag gesture is over the bounds of the component. When this method returns true, Swing shows the drop cursor and the drop location is visually indicated; when this method returns false, Swing shows the "no-drag" cursor and the drop location is not displayed.
For example, imagine a table that allows drop, but not in the first column. The canImport
method might look something like this:
public boolean canImport(TransferHandler.TransferSupport info) { // for the demo, we will only support drops (not clipboard paste) if (!info.isDrop()) { return false; } // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } // fetch the drop location JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation(); int column = dl.getColumn(); // we do not support invalid columns or the first column if (column == -1 || column == 0) { return false; } return true; }
The code displayed in bold indicates the location-sensitive drop logic: When the user drops the data in such a way that the column cannot be calculated (and is therefore invalid) or when the user drops the text in the first column, the canImport
method returns false — so Swing shows the "no-drag" mouse cursor. As soon as the user moves the mouse off the first column canImport
returns true and Swing shows the drag cursor.
Next, we show a demo of a tree that has implemented location-sensitive drop.