Sign in to follow this  

Keyboard Input

This topic is 4711 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm making snake with Java, and I have everything finished except for my keyboard input to make the snake move. I want to use a keyListener interface (keyPressed), but I cannot figure out how it works. Please help me!

Share this post


Link to post
Share on other sites
The basic idea is that whenever you run a java program, there are certain "events" to which the operating system "listens to" and send to your program. When you press a key on the keyboard a "key event" is triggered and your trying to just "listen" to that event and react to it.
First you need to have the Java class that you want to "listen" to these key events by implementing the interface KeyListener ( class JavaClass implements KeyListener ). Then you need to implement all of the member methods of the interface
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
(I think that's it). Finally you write code for each of these methods to do stuff when you press a key, and that's it! A case statement is really the easiest.

public void keyReleased(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_UP:
case KeyEvent.VK_W:
forwardStrafe = false;
break;
case KeyEvent.VK_DOWN:
case KeyEvent.VK_S:
backwardStrafe = false;
break;
case KeyEvent.VK_LEFT:
case KeyEvent.VK_A:
leftStrafe = false;
break;
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_D:
rightStrafe = false;
break;
default:
System.out.println("Key: " + e.getKeyCode()+" was released");
}
}

Share this post


Link to post
Share on other sites
I'm curious... after creating the KeyReleased, keyPressed and keyTyped Methods, how would one call them? What is passed as the parameter?

Share this post


Link to post
Share on other sites
Quote:
Original post by Kojo
I'm curious... after creating the KeyReleased, keyPressed and keyTyped Methods, how would one call them? What is passed as the parameter?


One doesn't call them. The system calls them automatically. The parameter is an object of type KeyEvent. Check the Java SDK docs for all the nitty-gritty details.

Share this post


Link to post
Share on other sites

This topic is 4711 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this