你能帮我修改一下这段代码:
public void keyPressed(KeyEvent e) { if (e.getKeyCode()==39) { //Right arrow key code } else if (e.getKeyCode()==37) { //Left arrow key code } repaint(); }
请注意如何检查向上/向下箭头键.谢谢!
public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); switch( keyCode ) { case KeyEvent.VK_UP: // handle up break; case KeyEvent.VK_DOWN: // handle down break; case KeyEvent.VK_LEFT: // handle left break; case KeyEvent.VK_RIGHT : // handle right break; } }
public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT ) { //Right arrow key code } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) { //Left arrow key code } else if (e.getKeyCode() == KeyEvent.VK_UP ) { //Up arrow key code } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) { //Down arrow key code } repaint(); }
KeyEvent代码都是API的一部分:http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
只是为了完成答案(使用KeyEvent是要走的路),但向上箭头是38,向下箭头是40,所以:
else if (e.getKeyCode()==38) { //Up arrow key code } else if (e.getKeyCode()==40) { //down arrow key code }