事件监听

鼠标监听

  • 实现鼠标画画
    Mouse
package com.shu.gui;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;

public class DrawPoint {
    public static void main(String[] args) {
        MyFrame myFrame = new MyFrame();
        myFrame.loadFrame();
        myFrame.startPaint();
    }


}

class MyFrame extends Frame{
    ArrayList<Point> points;

    public MyFrame(){
        super("Draw");
    }

    public void loadFrame(){
        setBackground(Color.LIGHT_GRAY);
        setBounds(100,100,400,300);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public void startPaint(){
        points=  new ArrayList<Point>();
        this.addMouseListener(new MyMouseListener());
    }

    @Override
    public void paint(Graphics g) {
        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point point = (Point) iterator.next();
            g.setColor(Color.BLUE);
            g.fillOval(point.x, point.y, 10, 10);
        }
    }

    public void addpoint(Point point){
        points.add(point);
    }

    private class MyMouseListener extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            MyFrame myFrame = (MyFrame) e.getSource();
            myFrame.addpoint(new Point(e.getX(), e.getY()));
            myFrame.repaint();
        }
    }



}



窗口监听

public class TestWindowsListener {
    public static void main(String[] args) {
        MyFrame myFrame = new MyFrame();
        myFrame.loadFrame();
        myFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowActivated(WindowEvent e) {
                Frame frame = (Frame)e.getSource();
                frame.setTitle("Activated");
            }
        });
    }
}

键盘监听

frame.addKeyListener(new KeyAdapter(){
    @Override
    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_UP){
            System.out.println("Press UP");
        }
    }
}
posted @ 2020-05-18 08:20  Archer_Shu  阅读(77)  评论(0编辑  收藏  举报