Chapter 9, Drag-and-Drop
#66 Handle Dropped URLs
H A C K
Handle Dropped URLs
Drag-and-drop is like a box of chocolates; you never know what you’re going
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
interface, which means your implementation will get callbacks
when the user drags the mouse into your component, over it, out of it, etc.
DropTarget’s methods can be left as no-ops; for now, only the drop( )
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
passed to you by the DropTargetDropEvent: it specifies, in order of robust-
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
which shows the
DataFlavors offered to you by the drop. You can use
System.out.println( ) on a particular flavor to get its MIME type, which
describes the contents of the drop, and a representation class, which indi-
cates how those contents will be provided to you by
. For example, some browsers will give you a java.net.
, whose DataFlavor looks like this:
One thing that’s surprising is the number of DataFlavors offered by popular
web browsers. Table 9-1 is a short listing of some of the browsers I tested.
Table 9-1. Browsers and their supported DataFlavors
Browser Supported DataFlavors
Firefox 1.0 / Windows XP 78
MSIE 6.0 / Windows XP 53
Safari 1.3 / Mac OS X 53
Firefox 1.0 / Mac OS X 30
MSIE 5.2.3 / Mac OS X 53