你的位置:首页 > Java教程

[Java教程]java编写一个可以上下移动的小球:运行后,可以通过上下左右键进行移动


/*
* 功能:加深对事件处理机制的理解
* 1.通过控制上下左右键,来控制一个小球的位置
*/
package com.test1;
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){
Demo9_4 demo_4 = new Demo9_4();
}
//构造函数
public Demo9_4(){
mp = new Mypanel();

this.add(mp);

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


//定义自己的面板
class Mypanel extends JPanel implements KeyListener{
int x=10;
int y=10;
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.red);
g.fillOval(x,y, 30, 30);
}

//键被按下
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
//System.out.println("键被按下"+(char)e.getKeyCode());

}

//键被按下
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode() == KeyEvent.VK_DOWN){
y+=5;

}else if(e.getKeyCode() == KeyEvent.VK_LEFT){
x-=5;
}else if(e.getKeyCode() == KeyEvent.VK_UP){
y-=5;
}else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
x+=5;
}

this.repaint();
}

//键一个值被输出
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}
}