aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes KeyListener that listens everywhere inside a JDialog Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "KeyListener that listens everywhere inside a JDialog" Watch "KeyListener that listens everywhere inside a JDialog" New topic
Author

KeyListener that listens everywhere inside a JDialog

Meyer Florian
Ranch Hand

Joined: Oct 20, 2003
Posts: 62
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
Ken Krebs
Ranch Hand

Joined: Nov 27, 2002
Posts: 451
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
Meyer Florian
Ranch Hand

Joined: Oct 20, 2003
Posts: 62
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!
Ken Krebs
Ranch Hand

Joined: Nov 27, 2002
Posts: 451
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 agree. Here's the link: http://aspose.com/file-tools
 
subject: KeyListener that listens everywhere inside a JDialog