這裡實現鍵盤監聽,監聽上下左右四個按鍵,操控小球上下左右移動,代碼如下:
import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Panel; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class KeyListenerDemo { public static void main(String[] args) { Frame frame = new Frame(); frame.setSize(800, 800); frame.setBackground(Color.BLACK); MyPanel myPanel = new MyPanel(); frame.add(myPanel); frame.addKeyListener(myPanel); myPanel.addKeyListener(myPanel); frame.show(); } } class MyPanel extends Panel implements KeyListener { int x = 150; int y = 150; @Override public void paint(Graphics g) { g.setColor(Color.WHITE); g.fillOval(x, y, 20, 20); } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 37) { x--; } else if (e.getKeyCode() == 38) { y -= 10; } else if (e.getKeyCode() == 39) { x += 10; } else if (e.getKeyCode() == 40) { y += 10; } repaint();// 不要忘了!!!!! } @Override public void keyReleased(KeyEvent e) {// 松開鍵盤,返回到起點 x = 150; y = 150; repaint(); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } }