1.键盘监听器:
1 class KeyFrame extends Frame { 2 public KeyFrame() { 3 setBounds(1,2,300,400); 4 setVisible(true); 5 6 this.addKeyListener(new KeyAdapter() { 7 //键盘按下 8 public void keyPressed(KeyEvent e) { 9 int keyCode = e.getKeyCode(); 10 if (keyCode == KeyEvent.VK_UP) { 11 System.out.println("按了上键"); 12 } 13 } 14 }); 15 }
2.鼠标监听器:
1 //适配器模式 2 private class MyMouseListener extends MouseAdapter{ 3 public void mousePressed(MouseEvent e) { 4 MyFrame frame = (MyFrame)e.getSource(); 5 //鼠标点击时,将会在界面上产生一个点 6 //这个点就是鼠标的点 7 frame.addPoint(new Point(e.getX(),e.getY())); 8 9 //每次点击鼠标都重新画一遍 10 frame.repaint(); 11 } 12 }
通过鼠标监听器实现画笔的功能:
1 class MyFrame extends Frame{ 2 ArrayList points; 3 //需要画笔,需要监听鼠标当前的位置,需要集合存储这个点 4 public MyFrame(String title) { 5 super(title); 6 setBounds(200,200,400,300); 7 setVisible(true); 8 //存鼠标点击的点 9 points = new ArrayList<>(); 10 //添加一个鼠标监听器 11 this.addMouseListener(new MyMouseListener()); 12 } 13 14 public void paint(Graphics g) { 15 //画画,监听鼠标的事件 16 Iterator iterator = points.iterator(); 17 while (iterator.hasNext()) { 18 Point point = (Point) iterator.next(); 19 g.setColor(Color.BLUE); 20 g.fillOval(point.x, point.y, 10, 10); 21 } 22 } 23 24 //添加一个点到界面上 25 public void addPoint(Point point) { 26 points.add(point); 27 } 28 29 //适配器模式 30 private class MyMouseListener extends MouseAdapter{ 31 public void mousePressed(MouseEvent e) { 32 MyFrame frame = (MyFrame)e.getSource(); 33 //鼠标点击时,将会在界面上产生一个点 34 //这个点就是鼠标的点 35 frame.addPoint(new Point(e.getX(),e.getY())); 36 37 //每次点击鼠标都重新画一遍 38 frame.repaint(); 39 } 40 } 41 }
3.窗口监听器:
1 class MyWindowListener extends WindowAdapter { 2 public void windowClosing(WindowEvent e) { 3 setVisible(false); 4 System.exit(0); 5 } 6 7 }
实例使用:
1 class WindowFrame extends Frame{ 2 public WindowFrame() { 3 setBackground(Color.blue); 4 setBounds(100,100,200,200); 5 setVisible(true); 6 addWindowListener(new MyWindowListener() { 7 public void windowClosing(WindowEvent e) { 8 setVisible(false); 9 } 10 11 public void windowActiated(WindowEvent e) { 12 System.out.println("windowActivated"); 13 } 14 }); 15 } 16 17 class MyWindowListener extends WindowAdapter { 18 public void windowClosing(WindowEvent e) { 19 setVisible(false); 20 System.exit(0); 21 } 22 23 } 24 }