Java Reference
In-Depth Information
Example 13−4: ScribbleDragAndDrop.java (continued)
Rectangle r = new Rectangle (x-LINEWIDTH, y-LINEWIDTH,
LINEWIDTH*2, LINEWIDTH*2);
int numScribbles = scribbles.size();
for(int i = 0; i < numScribbles; i++) { // Loop through the scribbles
Scribble s = (Scribble) scribbles.get(i);
if (s.intersects(r)) {
// The user started the drag on top of this scribble, so
// start to drag it.
// First, remember which scribble is being dragged, so we can
// delete it later (if this is a move rather than a copy)
beingDragged = s;
// Next, create a copy that will be the one dragged
Scribble dragScribble = (Scribble) s.clone();
// Adjust the origin to the point the user clicked on.
dragScribble.translate(-x, -y);
// Choose a cursor based on the type of drag the user initiated
Cursor cursor;
switch(e.getDragAction()) {
case DnDConstants.ACTION_COPY:
cursor = DragSource.DefaultCopyDrop;
break;
case DnDConstants.ACTION_MOVE:
cursor = DragSource.DefaultMoveDrop;
break;
default:
return; // We only support move and copys
}
// Some systems allow us to drag an image along with the
// cursor. If so, create an image of the scribble to drag
if (dragSource.isDragImageSupported()) {
Rectangle scribbleBox = dragScribble.getBounds();
Image dragImage = this.createImage(scribbleBox.width,
scribbleBox.height);
Graphics2D g = (Graphics2D)dragImage.getGraphics();
g.setColor(new Color(0,0,0,0)); // transparent background
g.fillRect(0, 0, scribbleBox.width, scribbleBox.height);
g.setColor(Color.black);
g.setStroke(linestyle);
g.translate(-scribbleBox.x, -scribbleBox.y);
g.draw(dragScribble);
Point hotspot = new Point(-scribbleBox.x, -scribbleBox.y);
// Now start dragging, using the image.
e.startDrag(cursor, dragImage, hotspot, dragScribble,this);
}
else {
// Or start the drag without an image
e.startDrag(cursor, dragScribble,this);
}
// After we've started dragging one scribble, stop looking
return;
}
}
}
Search WWH ::




Custom Search