填空题
本题中,鼠标在窗口中单击一下,就在单击的位置生成一个小矩形,如果在小矩形上双击鼠标左键,则删除小矩形。 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处:extends JPanel implements MouseMotionListener 第2处:s......(↓↓↓ 点击下方‘点击查看答案’看完整答案、解析 ↓↓↓)
点击查看答案&解析