import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class moveText{
Label myText;
Frame mT;
Point point = new Point(0, 0);
public moveText(){
myText=new Label("move me please!");
mT = new Frame("moveTEXT");
myText.setBackground(Color.yellow);
mT.addWindowListener(new myWindowListener());
mT.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
mT.setSize(600, 600);
mT.setLocation(100, 100);
myText.addMouseMotionListener(new myMouseListener1());
myText.addMouseListener(new myMouseListener2());
myText.setSize(20, 5);
mT.add(myText);
mT.setVisible(true);
}
class myMouseListener1 extends MouseMotionAdapter {
/*
当鼠标拖动时触发该事件。 记录下鼠标按下(开始拖动)的位置。
*/
public void mouseDragged(MouseEvent e) {
// 转换坐标系统,将新的坐标(鼠标相对于组件的坐标)转换成该相对与其组件的父亲组件的坐标
Point newPoint = SwingUtilities.convertPoint(myText, e
.getPoint(), myText.getParent());
// 设置标签的新位置
myText.setLocation(myText.getX()
+ (newPoint.x - point.x), myText.getY()
+ (newPoint.y - point.y));
//这时开始写的方法,明显和上面的方法差别很大
//myText.setLocation(newPoint);
// 更改坐标源点
point = newPoint;
}
}
class myMouseListener2 extends MouseAdapter{
/*
当鼠标按下时触发该事件。 记录下鼠标按下(开始拖动)的位置。
*/
public void mousePressed(MouseEvent e) {
// 得到当前坐标点
point = SwingUtilities.convertPoint(myText, e.getPoint(),
myText.getParent());
}
}
public static void main(String args[]){
moveText mT=new moveText();
}
}
class myWindowListener extends WindowAdapter{
public void windowClosing(WindowEvent e){//Frame的关闭方法
System.exit(0);
}
}