Skip to main content
GameDev.net gamedev.net
🔒 Locked

[java] 2 quick questions, help plz

Started by rma88 Nov 19, 2004 at 8:04 PM 5 replies 850+ views
Original Post
rma88
rma88
Hey guys, I got 2 quick questions that i was hoping someone on these boards could help me out w/. 1st: can someone give me a link or just type the ~3 lines of code to use a keylistener in java. at the beggining of my class i implements KeyListener. and i have the 3 methods keyPressed,keyReleased,keyTyped all overwritten. it compiles fine, but when i run, to test it...inside the keyPressed i had it do a prinln("a key was pressed"), and it never gets to it for some reason. 2nd: when i instantiate an object, what is the syntax for it? Image ship = ???? thanks guys, any help is greatly appreciated. -mitch
lucinpub
lucinpub
1. clicky Edit: from a google on: keylistener java tutorial
2. Image ship = new Image( parameters );
Lucas Henekswww.ionforge.com
rma88
rma88
hey, thanks for the replay, when u say:
"Image ship = new Image( parameters );"
what are the parameters though?is it the file name? "blah.gif" or something?

thanks all,
-mitch
pinacolada
pinacolada
Don't think you can make an Image that way, but if you have an Applet, you can call theApplet.getImage("blah.gif") to get an image object.

btw: for the key listener thing, I think the step you are missing is adding your object as a key listener- as in, calling addKeyListener() on all your components.
rma88
rma88
im not using an applet, but o well on the image thing, i'll mess w/ that later. as for the keylistener, this is bugging me. i have:
class classname implements KeyListener, Runnable
{
constructor(){}
...etc

public void keyPressed(KeyEvent e)
{
System.out.println("a key was pressed.");
}

public void keyReleased(KeyEvent e)
{
}

public void keyTyped(KeyEvent e)
{
}
}

is there something else im missing?
Pinacolada, where would i add addKeyListener();
srry, just trying to get this to work.

ty all ty, thanks for the help,
-mitch
pinacolada
pinacolada
Does the application make any windows or anything? It's been a while since I've worked with java applications, but I think you should have a Frame or a Window. Find that object, and the call looks like:

theFrameOrWindow.addKeyListener(theThingThatImplementsKeyListener);


And then, if you have any components inside your window, these can usually get keyboard focus at some point, so you want to call addKeyListener on them too.

Like, in that example that lucinpub posted, there is this block:
        typingArea = new JTextField(20);        typingArea.addKeyListener(this);

which means that any keys you press while the typingArea object has focus (as in, it's selected) will go to "this", which is the KeyEventDemo object.
Strife
Strife
...

BOTH of these questions could be very easily answered if you'd just look for the answer.

Closed.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.