if (shapeBeingDragged == null) return; int x = evt.getX(); int y = evt.getY(); Dimension cs = this.getSize(); int maxw = cs.width - shapeBeingDragged.width; int maxh = cs.height - shapeBeingDragged.height; if (x < 0) x = 0; else if (x > maxw) x = maxw; if (y < 0) y = 0; else if (y > maxh) y = maxh; shapeBeingDragged.moveBy(x, y); shapeBeingDragged = null; repaint();