Content area
Full Text
Summary - Drag and drop (D&D) is an intuitive GUI gesture used for transferring data from one GUI component to another. This article explores the D&D classes introduced in the Java 2 platform (formerly JDK 1.2). To demonstrate the transfer of textual data locally (within a single Java virtual machine) and remotely (to other JVMs or native programs), seasoned Java instructor Gene De Lisa shows you how to subclass a Swing (JFC) component. This article includes a A name="return1" href="#sidebar1" D&D Glossary. (4,000 words)
If you've ever selected a file icon in a filesystem browser like Windows Explorer and dragged it to an icon representing another directory (and it's likely you have), you've already used drag and drop to transfer data. If you'd like to use Java to transfer data, read on!
Java 2 (formerly JDK 1.2) introduced the ability to transfer data using the familiar drag and drop (D&D) metaphor. In Java 2, D&D utilizes the underlying data-transfer mechanism introduced in JDK 1.1 (java.awt.datatransfer) for use with the clipboard. Although this article discusses D&D operations in the context of GUI components, the specification includes no restrictions that prevent direct programmatic operations.
To develop the D&D metaphor, Java 2 defines several new classes in package java.awt.dnd. Please note: The GUI components used in this article are Swing components. In actuality, any subclass of java.awt.Component may be used.
First, we'll look at how a GUI component representing the data source of a D&D operation maintains an association with a java.awt.dnd.DropSource object.
Second, we'll examine how another GUI component representing the destination of the data of a D&D operation maintains an association with a java.awt.dnd.DropTarget object.
Finally, we'll wrap up with a java.awt.datatransfer.Transferable object that encapsulates the data transferred between the DragSource and DropTarget objects.
To download the source code in either zip or tar formats, see Resources.
DataFlavors and actions
When the Transferable object encapsulates data, it makes the data available to DropTarget in a variety of DataFlavors. For a local transfer within the same JVM (Java virtual machine), Transferable provides an object reference.
However, for transfers to another JVM or to the native system, this wouldn't make any sense, so a DataFlavor using a java.io.InputStream subclass usually is provided. (While a discussion of data...