以阅读代码为主:
import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; /** * Created by Administrator on 2015-10-15. */ public class ArrawKey extends JFrame { CirclePanel circlePanel = null; public static void main(String[] args) { ArrawKey arrawKey = new ArrawKey(); } //构造函数 public ArrawKey() { circlePanel = new CirclePanel(); this.add(circlePanel); this.addKeyListener(circlePanel); this.setSize(640, 480); this.setTitle("方向键控制小球实例"); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } //定义面板 class CirclePanel extends JPanel implements KeyListener { int x = 10; int y = 10; public void paint(Graphics graphics) { super.paint(graphics); graphics.fillOval(x, y, 10, 10); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_DOWN: y += 10; break; case KeyEvent.VK_UP: y -= 10; break; case KeyEvent.VK_RIGHT: x += 10; break; case KeyEvent.VK_LEFT: x -= 10; break; } this.repaint(); } @Override public void keyReleased(KeyEvent e) { } }