Java Reference
In-Depth Information
Example 13−3: ScribbleCutAndPaste.java (continued)
/** A simple main method to test the class. */
public static void main(String[] args) {
JFrame frame = new JFrame("ScribbleCutAndPaste");
ScribbleCutAndPaste s = new ScribbleCutAndPaste();
frame.getContentPane().add(s, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Dragging and Dropping Scribbles
Java 1.2 adds support for data transfer through drag-and-drop. The drag-and-drop
API is contained in the java.awt.dnd package and is built on top of the same
DataFlavor and Transferable architecture as cut-and-paste. Example 13-4 is a
Swing program that allows the user to scribble with the mouse in “draw” mode
and drag-and-drop scribbles in “drag” mode.
The drag-and-drop API is substantially more complex than the cut-and-paste API,
which is reflected in the length of this example. The key interfaces are DragGes-
tureListener , which triggers a new drag, and DragSourceListener and DropTar-
getListener , which notify the source of a drag and the target of a drop of
important events that occur during the drag-and-drop process. The example imple-
ments all three interfaces. Note that these interfaces define methods with similar
names and use a confusing variety of event types. For a more detailed description
of the drag-and-drop API, see Java Foundation Classes in a Nutshell .
While studying this example, you should pay particular attention to dragGesture-
Recognized() , which is where the drag is initiated, and drop() , which is where
data is actually transferred from source to target. This example uses a List of
Scribble objects; each Scribble object represents a single connected set of line
segments. This differs from Example 13-3, which uses a single Scribble to repre-
sent the entire scribble, including connected and disjoint line segments.
To test the program, start one copy and draw some lines with the mouse. Then
click on the Drag button and drag some lines with the mouse. Next, start another
copy of the program and drag lines from one program to the other. Note that the
Java drag-and-drop API can integrate with the native drag-and-drop system on
your computer; it uses the same mouse and keyboard bindings as native applica-
tions do. Usually, the default drag-and-drop operation is a move. But, by holding
down the appropriate modifier key, you can change it to a copy operation.
Example 13−4: ScribbleDragAndDrop.java
package com.davidflanagan.examples.datatransfer;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.datatransfer.*; // Clipboard, Transferable, DataFlavor, etc.
import java.awt.dnd.*;
import java.util.ArrayList;
Search WWH ::




Custom Search