首页 > 代码库 > 练习.键盘控制小球

练习.键盘控制小球

 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     @Override28     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     @Override45     public void keyReleased(KeyEvent e) {46     }47     @Override48     public void keyTyped(KeyEvent e) {49         50     }51 }

 

练习.键盘控制小球