views:

41

answers:

2

I've got a problem when trying to drag a JPanel. If I implement it purely in MouseDragged as:

public void mouseDragged(MouseEvent me) {
   me.getSource().setLocation(me.getX(), me.getY());
}

I get a weird effect of the moved object bouncing between two positions all the time (generating more "dragged" events). If I do it in the way described in this post, but with:

public void mouseDragged(MouseEvent me) {
   if (draggedElement == null)
      return;

   me.translatePoint(this.draggedXAdjust, this.draggedYAdjust);
   draggedElement.setLocation(me.getX(), me.getY());
}

I get an effect of the element bouncing a lot less, but it's still visible and the element moves only ½ of the way the mouse pointer does. Why does this happen / how can I fix this situation?

+1  A: 

Try this

final Component t = e.getComponent();
    e.translatePoint(getLocation().x + t.getLocation().x - px, getLocation().y + t.getLocation().y - py);

and add this method:

@Override
public void mousePressed(final MouseEvent e) {
    e.translatePoint(e.getComponent().getLocation().x, e.getComponent().getLocation().y);
    px = e.getX();
    py = e.getY();
}
Skip Head
With this, the dragged element jumps to the top-left corner of the window - but the dragging is predictable at least...
viraptor
Actually - this works without the translation in `mousePressed`. Still don't know why.
viraptor
A: 

I don't know if you can just do it using a mouseDragged event. In the past I use mousePressed to save the original point and mouse dragged to get the current point. In both cases I translate the points to the location on the screen. Then the difference between the two points is easily calculated and the location can be set appropriately.

My general purpose class for this is the Component Mover class.

camickr
Doesn't your method (saving position on screen) break if the dragging causes the viewing area to scroll?
viraptor
Must admit I've never tried dragging a component in a scroll pane.
camickr