本帖最后由 HM何伟 于 2013-4-7 22:23 编辑
为什么我这个小球不能移动啊- package TankGame;
- import java.awt.*;
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import javax.swing.*;
- public class DrawOval extends JFrame {
- MyPanel my = null;
- public static void main(String[] args) {
- DrawOval dr = new DrawOval();
- }
- public DrawOval() {
- my = new MyPanel();
- this.add(my);
- this.addKeyListener(my);
- 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, 15, 15);
- }
- @Override
- // 键被按下
- public void keyTyped(KeyEvent e) {
- if (e.getKeyCode() == KeyEvent.VK_KP_DOWN) {
- y++;
- } else if (e.getKeyCode() == KeyEvent.VK_KP_UP) {
- y--;
- } else if (e.getKeyCode() == KeyEvent.VK_KP_LEFT) {
- x--;
- } else if (e.getKeyCode() == KeyEvent.VK_KP_RIGHT) {
- x++;
- }
- this.repaint();
- }
- @Override
- // 键被松开
- public void keyPressed(KeyEvent e) {
- }
- @Override
- // 键的一个值被输出.
- public void keyReleased(KeyEvent e) {
- }
- }
复制代码 |