Question

This code is in my mouseDragged function and it drags the undecorated JFrame

if (mouse.y < 25 && !closePol.contains(mouse)){
    getParent().getParent().getParent().getParent().setLocation(new Point(e.getXOnScreen() - mouse.x, e.getYOnScreen() - mouse.y));
}

and I have code that sets mouse = new Point() whenever I move the mouse out of the JFrame. It works fine but there is a bug. Whenever I start dragging with mouse.y >= 25 and drag out the window, this this happens. The window moves the top left corner to the mouse.

Was it helpful?

Solution

As shown here, you need to offset your rendering point by the difference between the current mouse point and the previous mouse point. Give two instances of Point, textPt and mousePt,

this.addMouseMotionListener(new MouseMotionAdapter() {

    @Override
    public void mouseDragged(MouseEvent e) {
        int dx = e.getX() - mousePt.x;
        int dy = e.getY() - mousePt.y;
        textPt.setLocation(textPt.x + dx, textPt.y + dy);
        mousePt = e.getPoint();
        repaint();
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top