import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class JDialogTest extends JDialog{
JLabel jb=new JLabel("Test");
eventPerformed e=new eventPerformed();
JDialogTest()
{
this.setSize(400,300);
jb.setBounds(0,30,30,30);
this.getContentPane().setLayout(null);
jb.addMouseMotionListener(e);

this.getContentPane().add(jb);
show();
}
class eventPerformed extends MouseMotionAdapter{
// Point press=new Point();
// public void mousePressed(MouseEvent e){
// press.x=e.getX();
// press.y=e.getY();
// System.out.println (press);
// }
public void mouseDragged(MouseEvent e) {
JLabel j=(JLabel)e.getSource();
Point pt=j.getLocation();
j.setLocation(e.getX()+pt.x,e.getY()+pt.y);
//j.setLocation(e.getX(),e.getY());
System.out.println (e.getPoint());
j.getParent().repaint();
}
}
public static void main(String args[]){
new JDialogTest();
}
}
实现拖拽效果
j.setLocation()方法为什么要j.setLocation(e.getX()+pt.x,e.getY()+pt.y)才能正确显示
而这样直接设置却不行.setLocation(e.getX(),e.getY());
百思不得其解,有劳高手解释

解决方案 »

  1.   

    //j.setLocation(e.getX(),e.getY());
    System.out.println (e.getPoint()+"\t原坐标:"+ pt);用此语句查看便知.e.getX() 得到的是组件的相对位置!
      

  2.   

    即你向左拉,它得到的e.getX()是负数,向右则正
    e.getY()雷同.还有就是,一次拉动完后,每次移动的相对位置往往是很小值,(所以经常会是 -1,-2,+1,+2这样的幅度)因为还没移动多少的时候就被.getParent().repaint(),被重新定格了.