Keyboard Input

Started by
5 comments, last by BlackArrow 19 years, 2 months ago
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!
Advertisement
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");		}	}
That's perfect. Thanks much!
I'm curious... after creating the KeyReleased, keyPressed and keyTyped Methods, how would one call them? What is passed as the parameter?
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.
Can you give me an example of how to use them?
From the eternally useful Sun Java Tutorial, How to Write a Key Listener. While it applies more specifically to GUIs, the techniques are universal. Specifically, you might want to check out this example code.

This topic is closed to new replies.

Advertisement