Check out how I do this in my Draggable classs
you are welcome to use and modify this class, but please don't change the package or take credit for it as your own work
package tjacobs.ui;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* tjacobs.ui.Draggable
* Makes a component draggable. Does not work if there's a layout manager
* messing with things
* <code>
* usage:
* Component c = ...
* new Draggable(c);
* parent.add(c);
* </code>
*/
public class Draggable extends MouseAdapter implements MouseMotionListener {
Point mLastPoint;
Component mDraggable;
public Draggable(Component w) {
w.addMouseMotionListener(this);
w.addMouseListener(this);
mDraggable = w;
}
public Draggable(Window w, Component drag) {
drag.addMouseMotionListener(this);
drag.addMouseListener(this);
mDraggable = w;
}
public void mousePressed(MouseEvent me) {
if (mDraggable.getCursor().equals(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))) {
mLastPoint = me.getPoint();
}
else {
mLastPoint = null;
}
}
private void setCursorType(Point p) {
Point loc = mDraggable.getLocation();
Dimension size = mDraggable.getSize();
if ((p.y + WindowUtilities.RESIZE_MARGIN_SIZE < loc.y + size.height) && (p.x + WindowUtilities.RESIZE_MARGIN_SIZE < p.x + size.width)) {
mDraggable.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
}
public void mouseReleased(MouseEvent me) {
mLastPoint = null;
}
public void mouseMoved(MouseEvent me) {
setCursorType(me.getPoint());
}
public void mouseDragged(MouseEvent me) {
int x, y;
if (mLastPoint != null) {
x = mDraggable.getX() + (me.getX() - (int)mLastPoint.getX());
y = mDraggable.getY() + (me.getY() - (int)mLastPoint.getY());
mDraggable.setLocation(x, y);
}
}
}