Java Reference
In-Depth Information
Example 13−4: ScribbleDragAndDrop.java (continued)
/**
* This component can operate in two modes. In "draw mode", it allows the user
* to scribble with the mouse. In "drag mode", it allows the user to drag
* scribbles with the mouse. Regardless of the mode, it always allows
* scribbles to be dropped on it from other applications.
**/
public class ScribbleDragAndDrop extends JComponent
implements DragGestureListener,
// For recognizing the start of drags
DragSourceListener,
// For processing drag source events
DropTargetListener,
// For processing drop target events
MouseListener,
// For processing mouse clicks
MouseMotionListener
// For processing mouse drags
{
ArrayList scribbles = new ArrayList(); // A list of Scribbles to draw
Scribble currentScribble;
// The scribble in progress
Scribble beingDragged;
// The scribble being dragged
DragSource dragSource;
// A central DnD object
boolean dragMode;
// Are we dragging or scribbling?
// These are some constants we use
static final int LINEWIDTH = 3;
static final BasicStroke linestyle = new BasicStroke(LINEWIDTH);
static final Border normalBorder = new BevelBorder(BevelBorder.LOWERED);
static final Border dropBorder = new BevelBorder(BevelBorder.RAISED);
/** The constructor: set up drag-and-drop stuff */
public ScribbleDragAndDrop() {
// Give ourselves a nice default border.
// We'll change this border during drag-and-drop.
setBorder(normalBorder);
// Register listeners to handle drawing
addMouseListener(this);
addMouseMotionListener(this);
// Create a DragSource and DragGestureRecognizer to listen for drags
// The DragGestureRecognizer will notify the DragGestureListener
// when the user tries to drag an object
dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this, // What component
DnDConstants.ACTION_COPY_OR_MOVE, // What drag types?
this);// the listener
// Create and set up a DropTarget that will listen for drags and
// drops over this component, and will notify the DropTargetListener
DropTarget dropTarget = new DropTarget(this, // component to monitor
this); // listener to notify
this.setDropTarget(dropTarget); // Tell the component about it.
}
/**
* The component draws itself by drawing each of the Scribble objects.
**/
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(linestyle); // Specify wide lines
Search WWH ::




Custom Search