-1

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.

usama8800
  • 893
  • 3
  • 10
  • 20
  • If you don't get help soon, consider creating and posting a [Minimal, Complete, and Verifiable Example Program](http://stackoverflow.com/help/mcve) where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem. – Hovercraft Full Of Eels May 10 '14 at 14:02
  • 2
    By the way, your code with its getParent().getParent()... etc looks to be very fragile. I'd look for a more robust way of getting my references. – Hovercraft Full Of Eels May 10 '14 at 14:10
  • @HovercraftFullOfEels I tried using getRootPane() but it didnt work. Then I gave a name to my main pane and used getParent.getName() and kept adding getParents until i got it. – usama8800 May 10 '14 at 14:16
  • How about that [minimal complete example program](http://stackoverflow.com/help/mcve)? – Hovercraft Full Of Eels May 10 '14 at 14:23
  • And what is your desired appropriate behavior of this application? – Hovercraft Full Of Eels May 10 '14 at 14:49

1 Answers1

2

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();
    }
});
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045