我目前正在尝试在我的程序中实现一个键监听器,以便在我按下箭头键时它执行一个操作,我程序中的对象向左或向右移动。
这是我程序中的移动方法
public void moveDirection(KeyEvent e)
{
int move = 0;
int r = K.getRow();
int c = K.getCol();
if (e.getKeyCode() == 39) move = 1; //KeyEvent.VK_RIGHT
if (e.getKeyCode() == 37) move = 2; //KeyEvent.VK_LEFT
//if (e.getKeyCode() == KeyEvent.VK_DOWN) move = 3;
switch (move)
{
case 1: if (inBound(r, c+1))
K.setLocation(r ,c+1);
if (inBound(r, c-1) && frame2[r][c-1] == K)
frame2[K.getRow()][K.getCol()-1] = null;
break; //move right 39
case 2: K.setLocation(K.getRow(), K.getCol()-1); break; //move left 37
//case 3: b.setLocation(b.getRow()+1, b.getCol()); break; //move down
default: return;
}
processBlockList();
}
我想知道程序应该如何读取 (KeyEvent) e。我真的无法输入箭头键....
求助!
编辑:我还需要知道我需要添加到我的代码中的内容,以便我的程序在转到另一个方法之前等待大约 700 毫秒的键盘输入
最佳答案
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html 查看本教程
如果它是一个基于 UI 的应用程序,那么“我还需要知道我需要添加什么到我的代码中,以便我的程序在转到另一个方法之前等待大约 700 毫秒的键输入”,你可以使用 GlassPane 或 Timer 类满足要求。
对于关键事件:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
查看此游戏示例 http://zetcode.com/tutorials/javagamestutorial/movingsprites/
关于java - 如何使用KeyListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876491/