问题
When i press keyboard with F1 to 12 or 0 to 9 or A to Z (all buttons). I do not see its capturing my keyboard inputs. How do i fix this?
public class Boot extends JWindow implements KeyListener
{
public Boot()
{
.....
this.addKeyListener(this);
....
}
public void keyTyped(KeyEvent ke)
{
System.out.println( ke.getKeyChar());
}
public void keyPressed(KeyEvent ke)
{
System.out.println( ke.getKeyChar());
/* KEY EVENTS */
// KeyEvent.KEY_TYPED
// KeyEvent.KEY_PRESSED
// int id = id.getId();
}
public void keyReleased(KeyEvent ke)
{
System.out.println( ke.getKeyChar());
}
}
回答1:
KeyEvents are only passed to components that are focusable.
Read the API for the JWindow() constructor. It states:
Creates a window with no specified owner. This window will not be focusable.
Read the API for the JWindow(Frame) constructor. It states:
Creates a window with the specified owner frame. If owner is null, the shared owner will be used and this window will not be focusable. Also, this window will not be focusable unless its owner is showing on the screen.
So basically you also need to create a visible JFrame when using a JWindow.
JFrame frame = new JFrame();
frame.setVisible( true );
JWindow window = new JWindow(frame);
A hack I've seen on the forums is to use:
JWindow window = new JWindow(new JFrame("is Showing")
{
public boolean isShowing()
{
return true;
}
});
Or a better approach is to use an undecorated JFrame and you don't have to worry about this.
回答2:
[Java API of KeyEvent]
The getKeyChar method always returns a valid Unicode character or CHAR_UNDEFINED. Character input is reported by KEY_TYPED events: KEY_PRESSED and KEY_RELEASED events are not necessarily associated with character input. Therefore, the result of the getKeyChar method is guaranteed to be meaningful only for KEY_TYPED events.
For key pressed and key released events, the getKeyCode method returns the event's keyCode. For key typed events, the getKeyCode method always returns VK_UNDEFINED.
Use getKeyCode on key released. KeyEvent.F1, F2, ... are usable for the function keys.
来源:https://stackoverflow.com/questions/8066829/how-to-capture-keyboard-inputs-in-my-jwindow-using-java