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();
}
I am wondering how the program is supposed to read in (KeyEvent) e. I cannot really type in an arrowkey....
Please help!
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
The class which implements
KeyListener
interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such asJFrame
. SoMake one Key listener class as
Now our class
MyKeyListener
is ready to listen the key events. But it can not directly do so.Create any object like
JFrame
object through whichMyListener
can listen the key events. for that you need to addMyListener
object to theJFrame
object.http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html Check this tutorial
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.
For key Event:
check this game example http://zetcode.com/tutorials/javagamestutorial/movingsprites/
In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):
And by adding this to your constructor:
Or, if you are calling the function from a parent class/container:
And then doing all the KeyListener stuff mentioned by others.
Here is an SSCCE,
Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings