public class Demo extends JFrame{
MyPane mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo deom=new Demo();
}
public Demo(){
mp=new MyPane();
this.add(mp);
this.addKeyListener(mp);
this.setSize(400,300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
}
//任何類,只要實現了相應的接口,就可去監聽某個事件源
class MyPane extends JPanel implements KeyListener{
int x=10;
int y=10;
public void paint(Graphics g){
super.paint(g);
g.fillOval(x, y, 20, 20);
}ide
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
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++;
}
this.repaint();
}this
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}接口
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}事件
總結:一個類要實現監聽的步驟:
a.實現相應的接口(keylistener,mouselistener,actionlistener,windowlistener)
b.把接口的處理方法根據須要從新編寫(override)
c.在事件源註冊監聽
d.事件傳遞是靠事件類的
get