Sarin Suriyakoon
Sarin Suriyakoon

Reputation: 440

Java Keypressed event on netbeans gui does not work?

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

Answers (1)

dic19
dic19

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:

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

Related Questions