/**
* 功能:加深对事件处理机制的理解
* 1.通过上下左右键,来来控制一个小球的位置
*/
package 时间处理;
imp
imp
imp
public class Test2 extends JFrame{
MyPanel mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Test2 test2=new Test2();
}
//构造函数
public Test2()
{
mp=new MyPanel();
this.add(mp);
this.addKeyListener(mp);
this.addKeyListener(mp);
this.setSize(400,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//定义自己的面板
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);
}
//键被按下
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
//System.out.println(" 键被按下"+(char)e.getKeyChar());
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();
}
//键被释放
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
//键的一个值被输出
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}