填空题 本题中,鼠标在窗口中单击一下,就在单击的位置生成一个小矩形,如果在小矩形上双击鼠标左键,则删除小矩形。
import java. awt. * ;
import java. awt. event. * ;
import javax. swing. * ;
class MousePanel extends JPanel extends MouseMotionListener
public MousePanel()
addMouseListener(new MouseAdapter()
public void mousePressed(MouseEvent evt)
int x=evt. getX();
int y=evt. getY();
current=find(x, y);
if(current<0)
add(x, y);

public void mouseClicked(MouseEvent evt)
int x=evt. getX();
int y=evt. getY();
if(evt. getClickCount()>=2)
remove(current);


);
addMouseMotionListener(this);

public void paintComponent(Graphics g)
(super. paintComponent();
for (int i=0; i<nsquares; i++)
draw(g, i);

public int find(int x, int y)
for(int i=0; i<nsquares; i++)
if (squares[i]. x-SQUARELENGTH/2<=x&&
x<=squares[i], x+SQUARELENGTH/2
&&squares[i], y-SQUARELENGTH/2<=y
&&y<=squares[i]. y+SQUARELENGTH/2)
return i;
return-1;

public void draw(Graphics g, int i)
g. drawRect(squares[i]. x-SQUARELENGTH/2,
squares[i]. y-SQUARELENGTH/2,
SQUARELENGTH,
SQUARELENGTH);

public void add(int x, int y)
if(nsquares<MAXNSQUARES)
squares[nsquares]=new Point(x, y);
current=nsquares;
nsquares++;
repaint();


public void remove(int n)
if(n<0||n>=nsquares) return;
nsquares--;
squares[n]=squares[nsquares];
if(current==n) current=-1;
repaint();

public void mouseMoved(MouseEvent evt)

public void mouseDragged(MouseEvent evt)

private static final int SQUARELENGTH=10;
private static final int MAXNSQUARES=100;
private Point[] squares=new Point [MAXNSQUARES];
private int nsquares=0;
private int current=-1;

class MouseFrame extends JFrame
public MouseFrame()
setTitle("java3");
setSize(300,200);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System. exit(0);

);
Container contentPane=getContentPane();
contentPane. add (MousePanel());


public class java3
public static void main(String[] args)
JFrame frame=new MouseFrame();
frame. show();



  • 1、
【正确答案】 1、{{*HTML*}}第1处:extends JPanel implements MouseMotionListener
第2处:super. paintComponent(g)
第3处:eontentPane. add(new MousePanel())    
【答案解析】[解析] 第1处是继承Jpanel实现鼠标移动监听器接口;第2处以g为参数重新绘制组件;第3处在contentPane内容面板中添加一个MousePanel鼠标面板。