package secondpack; import java.awt.*; import java.awt.event.*; public class MyBall { public static void main(String args[]) { Frame w = new Frame(); w.setSize(800, 700); MyPanel mp = new MyPanel(); w.add(mp); w.addKeyListener(mp); mp.addKeyListener(mp); w.setBackground(Color.black); w.setVisible(true); } } class MyPanel extends Panel implements KeyListener { int x = 30; int y = 30; public void paint(Graphics g) { g.setColor(Color.red); g.fillOval(x, y, 20, 20); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { System.out.println(e.getKeyCode());//通过打印内容可以得到“上、下、左、右”键的值 if(e.getKeyCode() == 37) { x--; } if(e.getKeyCode() == 38) { y--; } if(e.getKeyCode() == 39) { x++; } if(e.getKeyCode() == 40) { y++; } repaint();//重画,这个很重要,没有这条命令,小球是不会有反应的 } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }