PDA

View Full Version : KeyListener


warhammerdude20
05-15-2004, 02:19 AM
so i am making a game, and i cant get the keylistener to work. all i have found were examples of using keylisteners for textareas and stuff. i want to add a keylistener on to the applet itself, how do i do this... this is what i have tryed...


import java.awt.*;
import java.applet.Applet;

public class Game extends Applet implements Runnable,KeyListener{
addKeyListener(this);

//run init and all that jazz

public void keyPressed(KeyEvent e){System.out.println(e.getKeyCode());}
public void keyReleased(KeyEvent e){System.out.println(e.getKeyCode());}


}


i could always just go like

public boolean keyDown(Event e,int Key){}

but its decrapitated or something like that...

so if anyone knows what im doing wrong, please help me fix it.

thanks...

shmoove
05-15-2004, 10:15 AM
Why is addKeyListener() out there? (I don't know if that's actually how you coded it or just a cut-down version of the code).
Have you tried putting the addKeyListener() bit inside one of the initialization methods?

shmoove

PS: Also, with applets you have to make sure that you click on the applet to get the keyboard input.

warhammerdude20
05-15-2004, 06:43 PM
I have, but it just said that Game, which is the class cant have a keylistener...

bawigga
05-15-2004, 09:43 PM
I just had a project in my computer science class and i had to figure out how to do this...

in your constructor for game class, do

public Game() {
this.setFocusable(true);
this.addKeyListener(this);
}

then along with your keyPressed() and keyReleased() implementations you also need to include keyTyped

public void keyTyped(KeyEvent e) {
//whatever you want it to do
}

if this helps good luck with your game.. if not instant message me...
aim: bawigga
yahoo bawigga
or email: bawigga@yahoo.com

also before i forget heres a good site that talks about KeyListeners...

http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html

warhammerdude20
05-16-2004, 12:13 AM
Hey,

thanks, i did that, and when it didnt work, i was mad, but then, i saw i wasnt importing java.awt.event.KeyEvent...

so now its working and my game is done!

so thanks shmoove and bawigga

bawigga
05-19-2004, 07:24 AM
aint no big thing, whats your game?