java 事件处理机制:按下上下左右键控制小球的运动

时间:2024-01-01 10:41:09

/**
* 加深对事件处理机制的理解
* 通过上下左右键来控制一个小球的位置
*/
package com.test3;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo9_4 extends JFrame{

MyPanel mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo9_4 Demo9_4=new Demo9_4();
}
public Demo9_4()
{
mp=new MyPanel();

this.add(mp);



this.addKeyListener(mp);
this.setSize(400,300);
this.setVisible(true);
}

}
//定义自己的面板
class MyPanel extends JPanel implements KeyListener{

int x=10;
int y=10;
public void paint(Graphics g)
{
super.paint(g);

g.fillOval(x, y, 10, 10);
}

@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
//System.out.println("anxia"+(char)e.getKeyCode());
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()函数,来重绘
this.repaint();

}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}
}