Hey there! I've got two questions: 1. How can I define a KeyListener for a JDialog and all of its subcomponents? When I add a KeyListener to the JDialog itself, it will not get invoked when I press a key (while the JDialog is active)... I simply want to add a KeyListener that listens on a keyPressed-Event. If the keyCode is VK_ENTER, a JButton should get invoked. 2. How do I programmatically invoke a JButton? Thank you very much! Greetz from the Praiser
Meyer, 1. The code snippet below shows a technique I have used in a subclass of a JDialog to do something similar to what you describe. In addition to having ActionListeners for the OK and Cancel JButtons I wanted to provide keyhandling as well. NOTE: I believe JOptionPane provides some handling of this problem in a similar way but I didn't want to use it for this particular circumstance. In fact, I may have lifted this technique from JOptionPane's source code but my aging memory cells can't confirm that.
2. My keyhandler invokes the same methods that the the JButton ActionListeners invoke. When you say "invoke a JButton" I think you mean you want to take the same action that the JButton will if it's pressed.
kktec<br />SCJP, SCWCD, SCJD<br />"What we observe is not nature itself, but nature exposed to our method of questioning." - Werner Heisenberg
Joined: Oct 20, 2003
Awww that's great, thank you very much, it's working... And another question: That JDialog only contains a JTextField and a OK-Button. When the User presses the enter key, the ok() function will get invoked. But now, I also want the JTextField to be focused when the user types text keys. Is that possible in any simple way or do I have to catch every Letter-Key? Thank you!
Joined: Nov 27, 2002
A quick glance at the Javadoc for KeyEvent shows that you can call getKetChar instead of getKeyCode and get the Unicode character to test against using Character's many utility methods.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: KeyListener that listens everywhere inside a JDialog