import java.awt.BasicStroke;
public class ScribbleDragAndDrop extends JComponent implements
DragGestureListener,
DragSourceListener,
DropTargetListener,
MouseListener,
MouseMotionListener
{
ArrayList scribbles = new ArrayList();
Scribble currentScribble;
Scribble beingDragged;
DragSource dragSource;
boolean dragMode;
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);
public ScribbleDragAndDrop() {
setBorder(normalBorder);
addMouseListener(this);
addMouseMotionListener(this);
dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE,
this);
DropTarget dropTarget = new DropTarget(this,
this);
this.setDropTarget(dropTarget);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(linestyle);
int numScribbles = scribbles.size();
for (int i = 0; i < numScribbles; i++) {
Scribble s = (Scribble) scribbles.get(i);
g2.draw(s);
}
}
public void setDragMode(boolean dragMode) {
this.dragMode = dragMode;
}
public boolean getDragMode() {
return dragMode;
}
public void mousePressed(MouseEvent e) {
if (dragMode)
return;
currentScribble = new Scribble();
scribbles.add(currentScribble);
currentScribble.moveto(e.getX(), e.getY());
}
public void mouseReleased(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
if (dragMode)
return;
currentScribble.lineto(e.getX(), e.getY());
repaint();
}
public void mouseMoved(MouseEvent e) {
}
public void dragGestureRecognized(DragGestureEvent e) {
if (!dragMode)
return;
MouseEvent inputEvent = (MouseEvent) e.getTriggerEvent();
int x = inputEvent.getX();
int y = inputEvent.getY();
Rectangle r = new Rectangle(x - LINEWIDTH, y - LINEWIDTH,
LINEWIDTH * 2, LINEWIDTH * 2);
int numScribbles = scribbles.size();
for (int i = 0; i < numScribbles; i++) {
Scribble s = (Scribble) scribbles.get(i);
if (s.intersects(r)) {
beingDragged = s;
Scribble dragScribble = (Scribble) s.clone();
dragScribble.translate(-x, -y);
Cursor cursor;
switch (e.getDragAction()) {
case DnDConstants.ACTION_COPY:
cursor = DragSource.DefaultCopyDrop;
break;
case DnDConstants.ACTION_MOVE:
cursor = DragSource.DefaultMoveDrop;
break;
default:
return;
}
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));
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);
e.startDrag(cursor, dragImage, hotspot, dragScribble, this);
} else {
e.startDrag(cursor, dragScribble, this);
}
return;
}
}
}
public void dragDropEnd(DragSourceDropEvent e) {
if (!e.getDropSuccess())
return;
int action = e.getDropAction();
if (action == DnDConstants.ACTION_MOVE) {
scribbles.remove(beingDragged);
beingDragged = null;
repaint();
}
}
public void dragEnter(DragSourceDragEvent e) {
}
public void dragExit(DragSourceEvent e) {
}
public void dropActionChanged(DragSourceDragEvent e) {
}
public void dragOver(DragSourceDragEvent e) {
}
public void dragEnter(DropTargetDragEvent e) {
if (e.isDataFlavorSupported(Scribble.scribbleDataFlavor)
|| e.isDataFlavorSupported(DataFlavor.stringFlavor)) {
e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
this.setBorder(dropBorder);
}
}
public void dragExit(DropTargetEvent e) {
this.setBorder(normalBorder);
}
public void drop(DropTargetDropEvent e) {
this.setBorder(normalBorder);
if (e.isDataFlavorSupported(Scribble.scribbleDataFlavor)
|| e.isDataFlavorSupported(DataFlavor.stringFlavor)) {
e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
e.rejectDrop();
return;
}
Transferable t = e.getTransferable();
Scribble droppedScribble;
try {
droppedScribble = (Scribble) t
.getTransferData(Scribble.scribbleDataFlavor);
} catch (Exception ex) {
try {
String s = (String) t.getTransferData(DataFlavor.stringFlavor);
droppedScribble = Scribble.parse(s);
} catch (Exception ex2) {
e.dropComplete(false);
return;
}
}
Point p = e.getLocation();
droppedScribble.translate(p.getX(), p.getY());
scribbles.add(droppedScribble);
repaint();
e.dropComplete(true);
}
public void dragOver(DropTargetDragEvent e) {
}
public void dropActionChanged(DropTargetDragEvent e) {
}
public static void main(String[] args) {
JFrame frame = new JFrame("ScribbleDragAndDrop");
final ScribbleDragAndDrop scribblePane = new ScribbleDragAndDrop();
frame.getContentPane().add(scribblePane, BorderLayout.CENTER);
JToolBar toolbar = new JToolBar();
ButtonGroup group = new ButtonGroup();
JToggleButton draw = new JToggleButton("Draw");
JToggleButton drag = new JToggleButton("Drag");
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scribblePane.setDragMode(false);
}
});
drag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scribblePane.setDragMode(true);
}
});
group.add(draw);
group.add(drag);
toolbar.add(draw);
toolbar.add(drag);
frame.getContentPane().add(toolbar, BorderLayout.NORTH);
draw.setSelected(true);
scribblePane.setDragMode(false);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
class Scribble implements Shape, Transferable, Serializable, Cloneable {
protected double[] points = new double[64];
protected int numPoints = 0;
double maxX = Double.NEGATIVE_INFINITY;
double maxY = Double.NEGATIVE_INFINITY;
double minX = Double.POSITIVE_INFINITY;
double minY = Double.POSITIVE_INFINITY;
public void moveto(double x, double y) {
if (numPoints + 3 > points.length)
reallocate();
points[numPoints++] = Double.NaN;
lineto(x, y);
}
public void lineto(double x, double y) {
if (numPoints + 2 > points.length)
reallocate();
points[numPoints++] = x;
points[numPoints++] = y;
if (x > maxX)
maxX = x;
if (x < minX)
minX = x;
if (y > maxY)
maxY = y;
if (y < minY)
minY = y;
}
public void append(Scribble s) {
int n = numPoints + s.numPoints;
double[] newpoints = new double[n];
System.arraycopy(points, 0, newpoints, 0, numPoints);
System.arraycopy(s.points, 0, newpoints, numPoints, s.numPoints);
points = newpoints;
numPoints = n;
minX = Math.min(minX, s.minX);
maxX = Math.max(maxX, s.maxX);
minY = Math.min(minY, s.minY);
maxY = Math.max(maxY, s.maxY);
}
public void translate(double x, double y) {
for (int i = 0; i < numPoints; i++) {
if (Double.isNaN(points[i]))
continue;
points[i++] += x;
points[i] += y;
}
minX += x;
maxX += x;
minY += y;
maxY += y;
}
protected void reallocate() {
double[] newpoints = new double[points.length * 2];
System.arraycopy(points, 0, newpoints, 0, numPoints);
points = newpoints;
}
public Object clone() {
try {
Scribble s = (Scribble) super.clone();
s.points = (double[]) points.clone();
return s;
} catch (CloneNotSupportedException e) {
return this;
}
}
public String toString() {
StringBuffer b = new StringBuffer();
for (int i = 0; i < numPoints; i++) {
if (Double.isNaN(points[i])) {
b.append("m ");
} else {
b.append(points[i]);
b.append(' ');
}
}
return b.toString();
}
public static Scribble parse(String s) throws NumberFormatException {
StringTokenizer st = new StringTokenizer(s);
Scribble scribble = new Scribble();
while (st.hasMoreTokens()) {
String t = st.nextToken();
if (t.charAt(0) == 'm') {
scribble.moveto(Double.parseDouble(st.nextToken()), Double
.parseDouble(st.nextToken()));
} else {
scribble.lineto(Double.parseDouble(t), Double.parseDouble(st
.nextToken()));
}
}
return scribble;
}
public Rectangle getBounds() {
return new Rectangle((int) (minX - 0.5f), (int) (minY - 0.5f),
(int) (maxX - minX + 0.5f), (int) (maxY - minY + 0.5f));
}
public Rectangle2D getBounds2D() {
return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
}
public boolean contains(Point2D p) {
return false;
}
public boolean contains(Rectangle2D r) {
return false;
}
public boolean contains(double x, double y) {
return false;
}
public boolean contains(double x, double y, double w, double h) {
return false;
}
public boolean intersects(Rectangle2D r) {
if (numPoints < 4)
return false;
int i = 0;
double x1, y1, x2 = 0.0, y2 = 0.0;
while (i < numPoints) {
if (Double.isNaN(points[i])) {
i++;
x2 = points[i++];
y2 = points[i++];
} else {
x1 = x2;
y1 = y2;
x2 = points[i++];
y2 = points[i++];
if (r.intersectsLine(x1, y1, x2, y2))
return true;
}
}
return false;
}
public boolean intersects(double x, double y, double w, double h) {
return intersects(new Rectangle2D.Double(x, y, w, h));
}
public PathIterator getPathIterator(AffineTransform at) {
return new ScribbleIterator(at);
}
public PathIterator getPathIterator(AffineTransform at, double flatness) {
return getPathIterator(at);
}
public class ScribbleIterator implements PathIterator {
protected int i = 0;
protected AffineTransform transform;
public ScribbleIterator(AffineTransform transform) {
this.transform = transform;
}
public int getWindingRule() {
return PathIterator.WIND_NON_ZERO;
}
public boolean isDone() {
return i >= numPoints;
}
public void next() {
if (Double.isNaN(points[i]))
i += 3;
else
i += 2;
}
public int currentSegment(float[] coords) {
int retval;
if (Double.isNaN(points[i])) {
coords[0] = (float) points[i + 1];
coords[1] = (float) points[i + 2];
retval = SEG_MOVETO;
} else {
coords[0] = (float) points[i];
coords[1] = (float) points[i + 1];
retval = SEG_LINETO;
}
if (transform != null)
transform.transform(coords, 0, coords, 0, 1);
return retval;
}
public int currentSegment(double[] coords) {
int retval;
if (Double.isNaN(points[i])) {
coords[0] = points[i + 1];
coords[1] = points[i + 2];
retval = SEG_MOVETO;
} else {
coords[0] = points[i];
coords[1] = points[i + 1];
retval = SEG_LINETO;
}
if (transform != null)
transform.transform(coords, 0, coords, 0, 1);
return retval;
}
}
public static DataFlavor scribbleDataFlavor = new DataFlavor(
Scribble.class, "Scribble");
public static DataFlavor[] supportedFlavors = { scribbleDataFlavor,
DataFlavor.stringFlavor };
public DataFlavor[] getTransferDataFlavors() {
return (DataFlavor[]) supportedFlavors.clone();
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return (flavor.equals(scribbleDataFlavor) || flavor
.equals(DataFlavor.stringFlavor));
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException {
if (flavor.equals(scribbleDataFlavor)) {
return this;
} else if (flavor.equals(DataFlavor.stringFlavor)) {
return toString();
} else
throw new UnsupportedFlavorException(flavor);
}
}