如何使用的KeyListener [英] How to use KeyListener
问题描述
目前我正在试图在我的计划实施的KeyListener,以便它的动作,当我pressed箭头键,我在程序的对象要么向左或向右移动。
I am currently trying to implement a keylistener in my program so that it does an action when I pressed an arrow key, the object in my program either moves left or right.
下面是运动的方法在我的程序
Here is the moving method in my program
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)方法如我真的不能输入一个arrowkey ....
I am wondering how the program is supposed to read in (KeyEvent) e. I cannot really type in an arrowkey....
请帮帮忙!
编辑:我还需要知道什么,我需要添加到我的code,这样我的程序移动到另一种方法之前会等待大约700毫秒的keyinput
edit: I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method
推荐答案
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
检查本教程
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html Check this tutorial
如果它是一个基于用户界面的应用程序,然后在我还需要知道什么,我需要添加到我的code,这样我的程序移动到另一种方法之前会等待大约700毫秒的keyinput你可以使用玻璃面板或定时器类来满足需求。
If it's a UI based application , then " I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method" you can use GlassPane or Timer class to fulfill the requirement.
有关关键事件:
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://zet$c$c.com/tutorials / javagamestutorial / movingsprites /
这篇关于如何使用的KeyListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!