开发者

Dragging JPanel

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开发者_如何学Python(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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜