标签:
1 package com.java7.keyboardcontrolmyball.main; 2 import java.awt.*; 3 import java.awt.event.*; 4 5 public class KeyboardControlMyBall { 6 public static void main(String[] args) { 7 Frame w = new Frame(); 8 w.setSize(300,400); 9 10 MyPanel mp = new MyPanel(); 11 w.add(mp); 12 13 w.addKeyListener(mp); 14 mp.addKeyListener(mp); 15 16 w.show(); 17 } 18 } 19 20 class MyPanel extends Panel implements KeyListener { 21 int x = 30; 22 int y = 30; 23 public void paint(Graphics g) { 24 g.fillOval(x, y, 20, 20); 25 } 26 27 @Override 28 public void keyPressed(KeyEvent arg0) { 29 if(arg0.getKeyCode() == 37) { 30 x--; 31 } 32 if(arg0.getKeyCode() == 38) { 33 y--; 34 } 35 if(arg0.getKeyCode() == 39) { 36 x++; 37 } 38 if(arg0.getKeyCode() == 40) { 39 y++; 40 } 41 // System.out.println(arg0.getKeyCode()); 42 repaint(); 43 } 44 @Override 45 public void keyReleased(KeyEvent e) { 46 } 47 @Override 48 public void keyTyped(KeyEvent e) { 49 50 } 51 }
标签:
原文地址:http://www.cnblogs.com/fatoland/p/4199378.html