Java KeyListener is giving me "Unknown keyCode:0x0"
class KeyDemoFrame extends JFrame implements KeyListener
{
String line1;
KeyDemoFrame()
{
setTitle("hello");
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true开发者_StackOverflow中文版);
addKeyListener(this);
}
public void keyTyped(KeyEvent e) {
line1 = e.getKeyText(e.getKeyCode());
JOptionPane.showMessageDialog(null, e.getKeyCode());
JOptionPane.showMessageDialog(null, e.getKeyText(e.getKeyCode()));
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
When I press any key, I get "0" for the first message dialog and "Unknown keyCode:0x0" for the second one.
What am I doing wrong?
Looks like you have non-US layout as a default one. Java doesn't like it and generates events with invalid keycodes. As a countermeasure you can assign US a primary layout.
Use e.getKeyChar()
You need to get KeyCode
in KeyPressed
event and then you can use it in KeyTyped
, of course the variable you will use have to be declared outside these two events.
From the Java Documentation for a KeyEvent:
getKeyCode
Returns: the integer code for an actual key on the keyboard. (For KEY_TYPED events, the keyCode is VK_UNDEFINED.)
You are using a keyTyped event, thus the value being returned is VK_UNDEFIED.
You can, however, just use the following to get the character that was typed:
JOptionPane.showMessageDialog(null, e.getKeyChar());
You may get three types of events: KEY_PRESSED
, KEY_RELEASED
, and KEY_TYPED
events. The first two are associated to the action of pressing and releasing keys on the keyboard (which may or may not result in a character being typed), while the third one is associated with character input:
- For
KEY_PRESSED
andKEY_RELEASED
events:e.getKeyCode()
returns a valid key codee.getKeyChar()
returnsCHAR_UNDEFINED
- For
KEY_TYPED
events:e.getKeyChar()
returns a valid Unicode chare.getKeyCode()
returnsVK_UNDEFINED
Your code is listening to KEY_TYPED
events, but then using e.getKeyCode()
which is only valid for KEY_PRESSED
and KEY_RELEASED
events.
You also need this to ctach the event, I think:
/**
* Notification that an event has occured in the AWT event
* system
*
* @param e Details of the Event
*/
public void eventDispatched(AWTEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
keyPressed((KeyEvent) e);
}
if (e.getID() == KeyEvent.KEY_RELEASED) {
keyReleased((KeyEvent) e);
}
if (e.getID() == KeyEvent.KEY_TYPED) {
keyTyped((KeyEvent) e);
}
}
精彩评论