本题中,鼠标在窗口中单击一下,就在单击的位置生成一个小矩形,如果在小矩形上双击鼠标左键,则删除

13 查阅

本题中,鼠标在窗口中单击一下,就在单击的位置生成一个小矩形,如果在小矩形上双击鼠标左键,则删除小矩形。 import java.awt.*; import java.awt.event.*; import javax swing.*; class MousePanel extends JPanel extends MouseMo- tionListener {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-SQUARE- LENGTH/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= -l; 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[MAX- NSQUARES]; private int nsquares=0; private int current=-l; } class MouseFrame. extends JFramc {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; } }

参考答案:

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

计算机二级