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 continously 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.