问题
The following code is not working. I am trying to move a player left, right, up, and, down using key pressed method but when i press the keys it does not respond. I did not paste the whole code just the part that moves the box there are other if statements to achieve movement of other contents.
public class innerClassKeyPressed {
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;
}
if (key == 82)
{
initLevel(currlevel);
} //R
if (key == 78)
{
currlevel++;
initLevel(currlevel);
}
if ( (key == KeyEvent.VK_LEFT ) && ( key == KeyEvent.VK_RIGHT ) &&
(key == KeyEvent.VK_UP ) && ( key == KeyEvent.VK_DOWN )) {
return;
}
for (int row=0; row < myArray.length; row++)
{
for (int column=0; column < myArray[row].length; column++)
{
if( myArray[row][column]== Contents.PLAYER) {
if (myArray[row+dy][column+dx] == Contents.BOX)
{
if (myArray[row+dy*2][column+dx*2] == Contents.EMPTY)
{
myArray[row+dy][column+dx]= Contents.PLAYER;
myArray[row][column]= Contents.EMPTY;
myArray[row+dy*2][column+dx*2]= Contents.BOX;
回答1:
KeyListeners
are notorious for not working (well actually they do, just not the way you think they should).
The problem with KeyListener
is that they will only react when the component they are registered to is focusable and has focus (also known as key board focus).
Instead, you should use Key Bindings as they allow to determine the focus state under which they are triggered.
回答2:
As I'm guessing your using a JFrame and Canvas to draw your player then I'm also going to presume this isnt working because you have not added the KeyListener to the JFrame.
For example:
JFrame frame = new JFrame();
frame.addKeyListener(keylistener);
来源:https://stackoverflow.com/questions/16028573/keylistener-is-not-working