Drag and Drop JPanel

I have a problem while trying to drag and drop JPanel. If I implement it exclusively in MouseDragged as:

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

I get the strange effect of a moving object bouncing between two positions all the time (generating more “draggable” events). If I do it as 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 the effect of an element that bounces a lot less, but it is still visible, and the element moves only 1/2 the path that the mouse pointer makes. Why is this happening / how can I fix this situation?

+3
source share
3 answers

try it

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();
}
+1

OK. , - , , . JPanel JFrame :

    @Override
    public void mousePressed(MouseEvent e) {
        if (panel.contains(e.getPoint())) {
            dX = e.getLocationOnScreen().x - panel.getX();
            dY = e.getLocationOnScreen().y - panel.getY();
            panel.setDraggable(true);
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (panel.isDraggable()) {
            panel.setLocation(e.getLocationOnScreen().x - dX, e.getLocationOnScreen().y - dY);
            dX = e.getLocationOnScreen().x - panel.getX();
            dY = e.getLocationOnScreen().y - panel.getY();
        }
    }

.getLocationOnScreen() mouseDragged.

+5

, , mouseDragged. mousePressed, , , . . , .

Component Mover.

+1

Source: https://habr.com/ru/post/1765390/


All Articles