Search code examples
javaswingdrag-and-dropmouseeventjlabel

Dragging a JLabel in a JPanel using Mouse Events


I'm using the MouseInputListener (MouseListener + MouseMotionListener) to drag and drop multiple JLabels in a JPanel. Here is an outline of what I do;

MouseClicked: check if there is any JLabel within the clicked area of JPanel; if yes, select it (paint it to a color,etc). If not, do nothing.

MouseDragged: If a JLabel is selected, setLocation of that JLabel using e.getX() and e.getY() of the event. If nothing is selected, do nothing.

MouseReleased: If a JLabel is selected, paint it back to its original color. Select nothing (maybe null). If not, do nothing.

These are all in JPanel; JPanel implements MouseInputListener.

So here is the problem: When the inital position of a JLabel is 0,0 say I move it to 10,10. And after the mouse release and nothing is selected, when I click on 0,0 it selects that JLabel; however it was supposed to select it if I click at 10,10 because this is its new position.

Now I think this might be because I'm using the wrong coordinates; I've heard that the coordinate values in JPanel are relative, so I have to do a subtraction (i.e. final-initial coordinates) everytime to get the correct coordinates. I did it, but it did not work either. Another possibility might be that Java is storing all the historical X and Y coordinates (so that everytime I click on a previous coord, I select that object) which is purely imagination!

What are your suggestions?

Thanks in advance.


Solution

  • Add the MouseMotionListener to each of the labels instead of adding it to the panel. Then you don't need to determine whether you clicked on a label or not.

    See the Component Mover for a general implementation. You would need to customize it to support the coloring requirement.

    Edit:

    If you add the listener to the panel then the coordinates will always be relative to the panel, not the label, so I'm not sure what the problem is. If you want to find if you clicked on a component then use the Container.getComponentAt(Point) method.

    If you need more help then post your SSCCE that demonstrates the problem.