Handle Dropped URLs #66
Chapter 9, Drag-and-Drop
|
339
HACK
The constructor does all the work needed to accept drops. Really, this just
consists of creating a
DropTarget, which requires a Component (the “Drop
here” label), and a class implementing the
DropTargetListener
interface.
In the
drop( )
method, you need to
acceptDrop( )
to begin the process of
handling the drop. Pull out the
Transferable
from the
DropTargetDropEvent
,
and look to see if it supports any
DataFlavor
s that your application can sup-
port. In this demo, I implemented this with simple
if/else statements to try
the
urlFlavor and the constant stringFlavor. Each block knows what the
drop can be cast to, so one block casts to a
URL
, while the other casts to a
String.
When your code is finished handling the drop—successfully or not—you
need to call
dropComplete( ) on the DropTargetDropEvent, and pass a boolean
to indicate whether the drop was successful. The host OS can use this infor-
mation to finish animating the drop; for example, by flying the drag image
back to its source if the drop failed.
Drag Away
When you run the application, the big drop target is obvious, as seen in
Figure 9-2. In this case, a URL is being dragged from the Shiira web browser
on Mac OS X.
Once you drop a URL on the target, the dropped URL replaces the text in
the
JTextField (as seen in Figure 9-3).
Figure 9-2. Dragging a URL to a Swing component
Figure 9-3. Swing component after handling a dropped URL

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.