-
事件处理机制
1. 让面板类实现 KeyListener 键盘监听器接口,并重写其中的方法
(1)keyTyped 方法监听字符输出,当字符输出后触发
(2)keyPressed 方法监听按下动作,当按键按下后触发
(3)keyReleased 方法监听抬起动作,当某个键松开后触发
2. 重写监听事件方法体后,还需调用 repaint 方法重绘面板
3. 将面板对象放入画框的监听器
在画框类的构造方法中加入 addKeyListener(mp);
public class Event01 extends JFrame {private MyPanel mp = null;public static void main(String[] args) {new Event01();}public Event01() throws HeadlessException {mp = new MyPanel();add(mp);setVisible(true);setSize(1200, 900);setDefaultCloseOperation(DISPOSE_ON_CLOSE);addKeyListener(mp);}
}class MyPanel extends JPanel implements KeyListener {int x = 10;int y = 10;@Overridepublic void paint(Graphics g) {super.paint(g);g.fillOval(x, y, 50, 50);}@Overridepublic void keyTyped(KeyEvent e) {}@Overridepublic void keyPressed(KeyEvent e) {if (e.getKeyCode() == KeyEvent.VK_DOWN) {// 按了下方向键y++;} else if (e.getKeyCode() == KeyEvent.VK_UP) {y--;} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {x--;} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {x++;}repaint();}@Overridepublic void keyReleased(KeyEvent e) {}
}