NexMat
NexMat

Reputation: 93

Gap between mouse on screen and JPanel on Dragndrop

I use JPanel to draw a square on the screen. When I use MouseDragged it works fine and goes wherever I want, almost. Each time I click on the square, the square automatically moves and the top left corner goes right under the mouse. How should I do so that the square doesn't replace itself and stays right under the mouse ? Thanks for any help.

Upvotes: 0

Views: 25

Answers (1)

afzalex
afzalex

Reputation: 8652

Keep an account of the difference between top-left coordinates of Component which you are moving and mousePressed location.
And when you get new position, just subtract that difference to it.
Here I have tried to explain it through coding. Let myJPanel be the component you want to move. Then here is the MouseAdapter that can work for you. New position is stored in newPosition variable.

new MouseAdapter(){
    int diffx = 0, diffy = 0;
    public void mousePressed(MouseEvent e) {
        Point topLeft = myJPanel.getLocation();
        Point mouseDn = e.getPoint();
        diffx = mouseDn.x - topLeft.x;
        diffy = mouseDn.y - topLeft.y;
    }

    public void mouseDragged(MouseEvent e) {
        Point mouseDr = e.getPoint();
        int newX = mouseDr.x - diffx;
        int newY = mouseDr.y - diffy;
        Point newPosition = new Point(newX, newY);
    }
};

Upvotes: 1

Related Questions