java语言的科学与艺术-编程练习10.4(改进)
1 /* 2 * 程序可以用鼠标拖拽话出一个矩形; 3 */ 4 import acm.graphics.*; 5 import acm.program.*; 6 import java.awt.event.*; 7 8 public class DrawRectangle extends GraphicsProgram{ 9 //鼠标侦听 10 public void run(){ 11 addMouseListeners(); 12 } 13 //鼠标按下事件 14 public void mousePressed(MouseEvent e){ 15 press = new GPoint(e.getPoint()); 16 rect = new GRect(0,0); 17 } 18 //鼠标拖拽事件 19 public void mouseDragged(MouseEvent e){ 20 double x = press.getX(); 21 double y = press.getY(); 22 double width = e.getX() - press.getX(); 23 double height = e.getY() - press.getY(); 24 //确保向左下方拖拽也能画出矩形; 25 if(width < 0 ){ 26 x = e.getX(); 27 width = -width; 28 } 29 //确保向上方拖拽也能画出矩形; 30 if(height < 0){ 31 y = e.getY(); 32 height = -height; 33 } 34 35 rect.setSize(width,height); 36 rect.setFilled(true); 37 add(rect, x, y); 38 } 39 private GPoint press; //记录鼠标按下的点; 40 private GRect rect; 41 }
设置 一个 Grect 实例变量,使用 setSize方法改变矩形大小
posted on 2012-12-20 12:33 mybluecode 阅读(176) 评论(0) 编辑 收藏 举报