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.
-
1ok. and what is stopping you from implementing that? Get the coordinates of the mouse, check if they 're (still) on that of the object.Stultuske– Stultuske2022年11月14日 13:11:09 +00:00Commented Nov 14, 2022 at 13:11
1 Answer 1
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.
Comments
Explore related questions
See similar questions with these tags.