鼠标事件适配器

                  1、 鼠标事件适配器:抽象类java.awt.event.MouseAdapter实现了MouseListener接口,可以使用其子类作为MouseEvent的监听器,只要重写其相应的方法即可、使用适配器可以避免监听器类定义没有必要的空方法(MyMouseAdapter.java)
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class MyMouseAdapter {
	public static void main(String args[]) {
		new MyFrame("drawing...");
	}
}

@SuppressWarnings("serial")
class MyFrame extends Frame {
	ArrayList<Point> points = null; //创建List容器,存放点

	@SuppressWarnings("unchecked")
	MyFrame(String s) {
		super(s);  //设置标题
		points = new ArrayList();
		setLayout(null);
		setBounds(300, 300, 400, 300);
		this.setBackground(new Color(204, 204, 255));
		setVisible(true);
		this.addMouseListener(new Monitor());//创建监听器
	}

	public void paint(Graphics g) { //画图重写paint
		Iterator<Point> i = points.iterator();
		while (i.hasNext()) {
			Point p = (Point) i.next();
			g.setColor(Color.BLUE);
			g.fillOval(p.x, p.y, 10, 10);
		}
	}

	public void addPoint(Point p) {
		points.add(p);   //添加鼠标点击的坐标
	}
}

class Monitor extends MouseAdapter { //鼠标监听器
	public void mousePressed(MouseEvent e) { //重写要copy
		MyFrame f = (MyFrame) e.getSource();  //得到事件源
		f.addPoint(new Point(e.getX(), e.getY()));//获得鼠标点击的坐标
		f.repaint();  //刷新当前图面,repaint()调用update(),update()调用paint()
	}
}

你可能感兴趣的:(java,F#)