Reputation: 440
I use Netbeans form template to build gui and add Keypress event on form(right-click > Event > KeyPressed) like a code below. But it seems System.out.print or another action does not perform anything. So how should I do to fix this problem?
private void formKeyPressed(java.awt.event.KeyEvent evt) {
char PressedChar = evt.getKeyChar();
System.out.print(PressedChar);
}
Upvotes: 0
Views: 2322
Reputation: 17971
So how should I do to fix this problem?
Swing is designed to be used with Key bindings which is a more flexible and reliable approach that brings with these benefits:
WHEN_FOCUSED
, WHEN_IN_FOCUSED_WINDOW
, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
Having said this, we'd rarely want to listen for any key pressed to do something but for some specific key stroke or key combination in order to perform some action. However if your use case is such then yes, you'll need a KeyListener
, but please take a look to this answer by @camickr to do it correctly.
See also this topic: Key bindings vs. key listeners in Java, and How to Use Key Bindings tutorial
Upvotes: 1