Keyboard input without text boxes
I have a class that extends JPanel and uses the Graphics class to display stuff on the window, but I'm having trouble finding out how to get keyboard input without making a text box or anything like that. I need to be able to get keyboard input, character-by-character, from the JPanel I already have opened. Does anyone know how to do this?
[349 byte] By [
Nonymousa] at [2007-10-1 18:00:42]

public class YourClass implements KeyListener{
/**
* Somewhere in your code
*/
panel.addKeyListener(this);//panel is the panel you wish to receive keyboard input
private static final short NEW_LINE = 10;
private String sentence = "";
public void keyTyped(KeyEvent keyEvent) {
char character = keyEvent.getKeyChar();
if(character == NEW_LINE){
dealWithInput(sentence);
sentence = "";
}else{
sentence+=character;
}
}
private void dealWithInput(String str){
//Use the string for whatever you want here
System.out.println(str);
}
}
For the panel to receive keyBoard input this way it must have the focus. (You must have clicked on it)
This makes your class implement KeyListener then registers itself as a keyListener on the panel. That way whenever a key is typed it is passed to
keyTyped(). KeyTyped then appends the character to sentence or if it is a newline character calls dealWithInput
Sorry pressed post instead of edit.
You'll also have to add the empty methods
public void keyPressed(KeyEvent keyEvent) {
}
public void keyReleased(KeyEvent keyEvent) {
}
from KeyListener
Hope this helps
Michael
Several things that are a bit off here.
1. I have been told by someone that the proper way to program keyobard commands for a frame or panel is to use the KeyboardFocusManager. See http://java.sun.com/j2se/1.5.0/docs/api/java/awt/KeyboardFocusManager.html
I tried it out and found it generally better about catching key events.
2.
>public void keyTyped(KeyEvent keyEvent) {
FYI: keyTyped events will come in in a manner similar to if you hold a key down. You get one right away, and then more if the key stays down. You may want to implement your own repeated keying by listening for keyPress and keyReleased and using a Timer while the key is down. Or you may just want pressing a key to only happen once. Or you may want keyTyped.
3.
> For the panel to receive keyBoard input this way it
> must have the focus. (You must have clicked on it)
You should also be very sure to call setFocusable(true). Most things (ie panels) are not focusable by default
> Several things that are a bit off here.Sorry this sounds too aggressive/negative. Everything the other poster said was correct, it's just there are some other, maybe better, ways.