JAVA 事件监听器/事件

时间:2021-12-29 22:39:07

事件:MouseEvent/ KeyEvent等等.

对于一个frame要addMouseListener( 你定义的监听事件)

例如:

class Monitor extends MouseAdapter.. 再实现对应的操作. 查API文档

在对应的frame类中,

定义paint.. paint的作用就是绘制. 自动绘制, 当窗口被覆盖等等..时候再出现时候会重绘制

paint会一直被调用的, 甚至是点击鼠标等

 

可以把graphics 看做是一支画笔, 画笔所使用的地方就是你当前this的对象..

repaint的作用, 强制窗口重绘. 首先调用repaint—> update[实现双缓冲]—> paint..

 

                         

 

事件源windows/frame/panel ect...,

监听器Listener,

处罚事件*Event.

画笔: graphics

 

 

import java.awt.*;
import java.awt.event.*;
import java.util.Collection.*;
import java.util.*;

public class test{
        public static void main(String args[]){
                new PaintFrame("My PaintBoader");
            }
    }
class PaintFrame extends Frame{
    ArrayList points = null;
    PaintFrame(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){
        Iterator 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 me ){
                PaintFrame pframe = (PaintFrame)me.getSource();
                pframe.addPoint(new Point(me.getX(), me.getY()));
                pframe.repaint();
            }
    }