且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

拖动JPanel

更新时间:2023-12-05 11:28:10

尝试这个

  final组件t = e.getComponent(); 
e.translatePoint(getLocation()。x + t.getLocation()。x - px,getLocation()。y + t.getLocation()。

并添加此方法:

  @Override 
public void mousePressed(final MouseEvent e){
e.translatePoint(e.getComponent()。getLocation()。x,e.getComponent()。getLocation ().Y);
px = e.getX();
py = e.getY();
}


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?

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