progy_rock progy_rock - 1 month ago 16
Java Question

Why isn't a key event triggered in my applet that displays a moving rectangle?

I have programmed an applet using

AWT
package that displays a blue rectangle initially moving horizontally from left to right on the canvas. What I want to do is change the direction of movement of the rectangle corresponding to the navigation key pressed on the keyboard. I'm provided with the
getKeyCode()
values of the navigation keys:

37 for


38 for


39 for


40 for


I've implemented the
java.awt.event.KeyListener
interface in the Applet class and added the
addKeyListener(this);
and
setFocusable(true);
statements in the
init()
method but the problem is that the the KeyEvent doesn't seem to trigger and the rectangle keeps moving east till infinity. I thought that there might be a logical flaw in the
paint()
method and to confirm that, I added a
System.out.println("...");
statement in the overriden
keyTyped()
method, but I don't see any output in the terminal window on pressing a key and so I am sure that the KeyEvent is not triggered.

I've gone through a couple of other questions on a KeyEvent not being triggered but I didn't find any help.

Below is the code of my applet class including the definition of
init()
,
paint()
and
keyTyped()
methods for your reference.

public class MyApplet extends Applet implements KeyListener {
int x,y,lx,ly;

@Override
public void init(){
lx=0; ly=0; x=2; y=0;
addKeyListener(this);
setFocusable(true);
}

@Override
public void keyTyped(KeyEvent K){
int c = K.getKeyCode();

if(c==37){
x=-2;
y=0;
}
if(c==38){
y=-2;
x=0;
}
if(c==39){
x=2;
y=0;
}
if(c==40){
y=2;
x=0;
}

System.out.println("value changed on key type: X = "+x+" | Y = "+y+"\n");

repaint();
}

@Override
public void paint(Graphics g){
g.setColor(Color.blue);
g.fillRect(lx,ly,50,25);
try{
Thread.sleep(50);
}
catch(Exception e){
System.err.println(e);
}
g.setColor(Color.white);
g.fillRect(lx,ly,50,25);
lx+=x; ly+=y;
repaint();
}
}


VARIABLES' INFO:

int x
: value by which rectangle's horizontal coordinates change ([+] = right; [-] = left)

int y
: value by which rectangle's vertical coordinates change ([+] = down; [-] = up)

int lx, ly
: coordinates to draw the rectangle at in the paint method (values of
lx
and
ly
get incremented by
x
and
y
respectively in the main method after drawing the rectangle every time).

So, my question is, WHY IS THE KEY EVENT NOT TRIGGERED IN THIS APPLET?

I'd really appreciate any help in this matter.

Answer

"KeyPressed and KeyReleased events are the only way to find out about keys that don't generate character input."

Therefore you have to switch keyTyped() with keyPressed().