Dragging JPanel

我的梦境 提交于 2019-12-07 19:16:09

问题


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:


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



回答2:


OK. Old question but if anyone comes across this like I did this can be solved relatively simply. For dragging a JPanel in a JFrame I did:

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

The key is to use .getLocationOnScreen() and update the adjustment at the end of each call of mouseDragged.




回答3:


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.



来源:https://stackoverflow.com/questions/3740141/dragging-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!