The Java Tutorials have been written for 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.
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
The following demo, LocationSensitiveDemo
, shows a JTree
that has been configured to support drop on any node except for one called "names" (or its descendants). Use the text field at the top of the frame as the drag source (it will automatically increment the string number each time you drag from there).
A combo box below the tree allows you to toggle the behavior for showing the drop location. Swing's default behavior is to show the drop location only when the area can accept the drop. You can override this behavior to always show the drop location (even if the area cannot accept the drop) or to never show the drop location (even if the area can accept the drop).
LocationSensitiveDemo
using
Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.The canImport
method for
looks like this:LocationSensitiveDemo
public boolean canImport(TransferHandler.TransferSupport info) { // for the demo, we will only support drops (not clipboard paste) if (!info.isDrop()) { return false; } String item = (String)indicateCombo.getSelectedItem(); if (item.equals("Always")) { info.setShowDropLocation(true); } else if (item.equals("Never")) { info.setShowDropLocation(false); } // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } // fetch the drop location JTree.DropLocation dl = (JTree.DropLocation)info.getDropLocation(); TreePath path = dl.getPath(); // we do not support invalid paths or descendants of the names folder if (path == null || namesPath.isDescendant(path)) { return false; } return true; }
The first code snippet displayed in bold modifies the drop location feedback mechanism. If "Always", then the drop location is always shown. If "Never", the drop location is never shown. Otherwise, the default behavior applies.
The second code snippet displayed in bold contains the logic that determines whether the tree will accept the data. If the path is not a valid path or if it is not the names path (or its descendant) it will return false and the import will not be accepted.