日期:2014-05-20 浏览次数:20731 次
import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.*; public class Round extends JPanel implements KeyListener, Runnable { public static final int UP = 1; public static final int DOWN = 2; public static final int LEFT = 3; public static final int RIGHT = 4; public static final int NULL = 5; int forward = NULL; int x=0; int y=0; public void paint(Graphics g) { super.paint(g); super.paintComponent(g); g.fillOval(x,y,20,20); //I.setBounds(x,y,icon.getIconWidth(),icon.getIconHeight()); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) {//按下按移动 if((e.getKeyCode()==KeyEvent.VK_A||e.getKeyCode()==KeyEvent.VK_LEFT)&&x>-10) { /*x-=2; this.repaint();*/ if (forward == NULL) { forward = LEFT; } } else if((e.getKeyCode()==KeyEvent.VK_D||e.getKeyCode()==KeyEvent.VK_RIGHT)&&x<878) { /*x+=2; this.repaint();*/ if (forward == NULL) { forward = RIGHT; } } else if((e.getKeyCode()==KeyEvent.VK_W||e.getKeyCode()==KeyEvent.VK_UP)&&y>-10) { /*y-=2; this.repaint();*/ if (forward == NULL) { forward = UP; } } else if((e.getKeyCode()==KeyEvent.VK_S||e.getKeyCode()==KeyEvent.VK_DOWN)&&y<878) { /*y+=2; this.repaint();*/ if (forward == NULL) { forward = DOWN; } } else { forward = NULL; } } public void keyReleased(KeyEvent e) { if((e.getKeyCode()==KeyEvent.VK_A||e.getKeyCode()==KeyEvent.VK_LEFT)&&x>-10) { /*x-=2; this.repaint();*/ if (forward == LEFT) { forward = NULL; } } else if((e.getKeyCode()==KeyEvent.VK_D||e.getKeyCode()==KeyEvent.VK_RIGHT)&&x<878) { /*x+=2; this.repaint();*/ if (forward == RIGHT) { forward = NULL; } } else if((e.getKeyCode()==KeyEvent.VK_W||e.getKeyCode()==KeyEvent.VK_UP)&&y>-10) { /*y-=2; this.repaint();*/ if (forward == UP) { forward = NULL; } } else if((e.getKeyCode()==KeyEvent.VK_S||e.getKeyCode()==KeyEvent.VK_DOWN)&&y<878) { /*y+=2; this.repaint();*/ if (forward == DOWN) { forward = NULL; } } } public void run() { while (true) { switch (forward) { case UP: y -= 2; System.out.println("UP"); break; case DOWN: y += 2; System.out.println("DOWN"); break; case LEFT: x -= 2; System.out.println("LEFT"); break; case RIGHT: x += 2; System.out.println("RIGHT"); break; } this.repaint(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } }