0

I would want my mouse positions to get detected for dragging object. I want the object will be able to be dragged only when the mouse cursor is pointing at the object

I can drag the object with .setObjPos(e.getX(),e.getY()). But the object keep jump to wherever the mouse cursor is. I want the object can only be dragged when the mouse cursor pointing at the object.

asked Nov 14, 2022 at 13:09
1
  • 1
    ok. and what is stopping you from implementing that? Get the coordinates of the mouse, check if they 're (still) on that of the object. Commented Nov 14, 2022 at 13:11

1 Answer 1

2

You can achieve this quite easily by implementing a custom MouseListener:

public final class DragListener extends MouseInputAdapter {
 private Point location;
 private MouseEvent pressed;
 public DragListener() {
 }
 public void mousePressed(final MouseEvent me) {
 pressed = me;
 }
 public void mouseDragged(final MouseEvent me) {
 if (pressed == null) {
 return;
 }
 Component component = me.getComponent();
 location = component.getLocation(location);
 int x = location.x - pressed.getX() + me.getX();
 int y = location.y - pressed.getY() + me.getY();
 component.setLocation(x, y);
 }
}

You can then add this custom Listener to any component like so:

DragListener dragListener = new DragListener();
frame.addMouseListener(dragListener);
frame.addMouseMotionListener(dragListener);

This will detect the MouseEvents on the component it is set to and only drag the component while the left mouse button is being pressed.

answered Nov 14, 2022 at 13:22
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.