(说明)
以下程序实现了利用鼠标任意移动该圆形的位置,仔细阅读代码和相关注释,将程序补充完整。
(代码6)
import java.awt.*;
import java.awt.event.*;
public class CIUSAMPLE extends Frame. implements MouseMotionListener, MouseListener
{
static CIUSAMPLE frm=new CIUSAMPLE ();
int x=70,y=60,posX=70,posY=60,dx,dy;
public static void main ( String args[])
{
frm.setTitle ("Dragging a circle");
frm.setSize ( 200,150 );(1)
frm.addMouseMotionListener ( frm );
frm. setVisible ( true );
}
public void mousePressed ( MouseEvent e )
{(2)
dy=e.getY () -posY;
}
public void mouseDragged ( MouseEvent e )
{(3)
y=e.getY () -dy;
if ( dx>0 && dx<50 && dy>0 && dy<50 ) //如果指我落在正方形区域内
{
G.raphics g=getGraphics ();(4)
}
}
public void paint ( Graphics g )
{
g.setColor ( Color. pink ); // 设置绘图颜色为粉红
g.fillOval ( x,y,50,50 ); //以基准点为图形的左上角绘出圆形(5)
posY=y;
}
public void mouseMoved ( MouseEvent e ) { }
public void mouseReleased ( MouseEvent e ) { }
public void mouseEntered ( MouseEvent e ) { }
public void mouseExited ( MouseEvent e ) { }
public void mouseClicked ( MouseEvent e ) { }
}