拖动JPanel [英] Dragging JPanel

查看:159
本文介绍了拖动JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试拖动JPanel时,我遇到问题。如果我纯粹在MouseDragged中实现它:

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

我得到一个奇怪的影响,移动的对象弹跳两个位置之间的时间(产生更多的拖动事件)。如果我按照这篇文章所描述的方式执行,但是:$ / $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

$ b $

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

我得到的元素的效果反弹了很少,但它仍然可见而元素只移动鼠标指针的一半。为什么会发生这种情况/如何解决这个问题?

解决方案

尝试这个

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

这篇关于拖动JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆