1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 import javax.swing.event.*; 5 public class moveText{ 6 Label myText; 7 Frame mT; 8 Point point = new Point(0, 0); 9 public moveText(){ 10 myText=new Label("move me please!"); 11 mT = new Frame("moveTEXT"); 12 myText.setBackground(Color.yellow); 13 14 mT.addWindowListener(new myWindowListener()); 15 mT.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10)); 16 mT.setSize(600, 600); 17 mT.setLocation(100, 100); 18 myText.addMouseMotionListener(new myMouseListener1()); 19 myText.addMouseListener(new myMouseListener2()); 20 myText.setSize(20, 5); 21 mT.add(myText); 22 23 mT.setVisible(true); 24 } 25 class myMouseListener1 extends MouseMotionAdapter { 26 27 /* 28 当鼠标拖动时触发该事件。 记录下鼠标按下(开始拖动)的位置。 29 */ 30 public void mouseDragged(MouseEvent e) { 31 // 转换坐标系统,将新的坐标(鼠标相对于组件的坐标)转换成该相对与其组件的父亲组件的坐标 32 Point newPoint = SwingUtilities.convertPoint(myText, e 33 .getPoint(), myText.getParent()); 34 // 设置标签的新位置 35 36 myText.setLocation(myText.getX() 37 + (newPoint.x - point.x), myText.getY() 38 + (newPoint.y - point.y)); 39 40 //这时开始写的方法,明显和上面的方法差别很大 41 //myText.setLocation(newPoint); 42 43 // 更改坐标源点 44 point = newPoint; 45 } 46 } 47 class myMouseListener2 extends MouseAdapter{ 48 /* 49 当鼠标按下时触发该事件。 记录下鼠标按下(开始拖动)的位置。 50 */ 51 public void mousePressed(MouseEvent e) { 52 // 得到当前坐标点 53 point = SwingUtilities.convertPoint(myText, e.getPoint(), 54 myText.getParent()); 55 } 56 } 57 public static void main(String args[]){ 58 moveText mT=new moveText(); 59 60 } 61 } 62 63 class myWindowListener extends WindowAdapter{ 64 public void windowClosing(WindowEvent e){//Frame的关闭方法 65 System.exit(0); 66 } 67 }
移动组件练习
时间: 2024-11-06 04:38:13