[说明]
以下程序实现了在applet里移动图形文件,仔细阅读代码和相关注释,将程序补充完整。
[代码6-1]
import j ava. awt. *;
import j ava.awt.event.*;
import java.applet. Applet;
public class AppCIU extends Applet implements MouseMotionListener, MouseListener
Image img;// 声明 Image 类类型的变量 img
int x=70,y=60,posX=70,posY=60,dx,dy;
public void init ( )
img=getImage ( getCodeBase ( ) ,"mouse.gif" ); //载入影像
addMouseListener ( this );
addMouseMotionListener ( this );
public void mousePressed ( MouseEvent e )
dx=e.getX()-posX; //取得按下之点与基准点X方向的距离
dy=e.getY()-posY; //取得按下之点与基准点Y方向的距离
public void mouseDragged ( MouseEvent e )
(1)
(2)
if ( dx>0 && dx<120 && dy>0 && dy<60 ) //如果指针落在图形上方
Graphics g=getGraphics ( );
(3)
public void paint ( Graphics g )
(4)
(5)
(6)
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 ) ;
参考答案:(A)x=e.getX()-dx;
(B)y=e.getY()-dy;
(C)update(g);
(D)g.drawImage(imgx,y,AB0,F0,this);
(E)posX=x;
(F)posY=y;
注:其中(A)和(B)可互换。(E)和(F)可互换。
解析:
本题程序实现了在applet里移动图形文件。对于(1)为取得拖曳时基准点的X坐标[x=e.getX()-dx]; (2)取得拖曳时基准点的Y坐标[y=e.getY()-dy];(3)清空画面为背景颜色,再调用paint()[update(g)]; (4)将img画在applet上[g.drawImage(img,x,y,120,60,this);];(5)更新基准点的X坐标[posX=x;];(6)更新基准点的Y坐标[posY=y;]。