
336
|
Chapter 9, Drag-and-Drop
#66 Handle Dropped URLs
HACK
H A C K
#66
Handle Dropped URLs
Hack #66
Drag-and-drop is like a box of chocolates; you never know what you’re going
to get....
Bookmark menus are so 1995. Today, you should expect to be able to drag
URLs to other applications and have those applications open web pages,
store the address in a bookmark database, start an email in response to a
mailto: URL, etc. Java’s networking chops are well-established and aren’t
the problem here. The issue is actually getting the URL itself from the drop.
To accept drops of native objects, your GUI needs to designate some
Component as the onscreen drop target. Your code then implements the
DropTarget
interface, which means your implementation will get callbacks
when the user drags the mouse into your component, over it, out of it, etc.
Most of
DropTarget’s methods can be left as no-ops; for now, only the drop( )
method matters.
What’s interesting about native drag-and-drop (and copy-and-paste, for that
matter) is that there’s not necessarily one way to represent the data being
transferred. Instead, you do a sort of negotiation with the
Transferable
passed to you by the DropTargetDropEvent: it specifies, in order of robust-
ness, which
DataFlavors it can deliver, or you ask whether specific
DataFlavors are supported.
In the demo code in Example 9-3, I have a method called
dumpDataFlavors( ),
which shows the
DataFlavor ...