The best (?) way is to use a KeyListener. http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/KeyEvent.html
In the class that you want the keyevent to occur, put this in your class declaration implements KeyListener {
Then somewhere in that class, put addkeyListener(this);
. You need to have three methods in this class - keyTyped(KeyEvent e), keyPressed(KeyEvent e) and keyReleased(KeyEvent e).
Here's a sample.
public class Example extends JFrame implements KeyListener
{
//some code goes here...
public void keyTyped (KeyEvent event) {}
public void keyReleased (KeyEvent event) {}
public void keyPressed (KeyEvent event)
{
int key = event.getSource();
if (key == KeyEvent.VK_UP)
{
//etc.
}
}
A tip is to use Boolean variables to keep track if a key is being pressed, something like
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 1) {
someButton = true;
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 1) {
someButton = false;
}
}