You can add a KeyListener
to your JFrame
. Here is an excellent tutorial.
Example
Let's create a class that implements our KeyListener
, and let's assume you've got a class that extends JFrame
, called Program
.
public class KeyMapper implements KeyListener
{
// Lots of methods will need to be written. I won't do them all.
private Program world;
public KeyMapper(Program world)
{
this.world = world;
}
/**
* This is the event that fires when a key is hit.
* @param e the event object passed when a key is hit.
* @Override
*/
public void keyTyped(KeyEvent e) {
if(e.getKeyChar() == 't') {
world.callMethod();
}
}
}
KeyMapper
will now call a method in your program, whenever t
is hit. To add this to your Program
, you can use the following line:
this.addKeyListener(new KeyMapper(this));