KeyListeners and KeyEvents
Hey, I decided that because when I set out to make a game 5 days ago, and I couldn't because I didn't know how to control stuff with the keyboard, I needed to learn how to create a program that could do something like this, but I had no idea how. I searched on the internet for hours, and eventually gave up and resorted to mouse events, from copied and pasted code. Then, someone contacted me and asked me to send them the code I had used for KeyListeners, and I told them I hadn't because I didn't know how, and that kind person gave me this gem.
The first thing you need to do is in the class you want to move, you must implement KeyListener
Code :
public class Example implements KeyListener{
/* Other game stuff (updates, constructors, other stuff) */
}
In the class that you implemented KeyListener, you need the instance of the window or canvas that you're using and you need to do
Code :
(instance of game window or canvas).addKeyListener(this);
Then you need to add 3 methods in the same class because they are abstract in KeyListener and need to be over written since you're implementing KeyListener
Code :
public void keyPressed(KeyEvent e){
}//key being held down
public void keyReleased(KeyEvent e){
}//key released
public void keyTyped(KeyEvent e){
}//not exactly sure, I never use
After that, all you need to do is make the game recognize the keys and give it actions for them
In public void keyPressed(KeyEvent e) or whichever void you want to use that you just added (the code above), you need to add
Code :
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
}
Then you have to check the int against the possible codes for keys (java has them built in)
so
Code :
public void keyPressed(KeyEvent e){
int key = e.getKeyCode():
if(key == KeyEvent.VK_SPACE){
System.out.println("Pressed Space");
}
}
would say Pressed Space whenever you hit space
if your using eclipse, you can get all the keycodes when you type if(key == KeyEvent.), it'll bring up the keycodes
After that I was fine, and I was able to make my game functional!
Hooray for that!
Re: KeyListeners and KeyEvents
Glad you got your game functioning. To add to your post, here are two tutorials which are helpful on this subject:
How to Write a Key Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)
How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
One should also note that for a KeyListener to function, the component must have focus (KeyBindings can be configured to overcome this). One should also read the API for KeyEvent - noting the difference between the keyTyped/keyPressed/keyReleased may produce different values for the getKeyCode/getKeyChar methods.