Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

KeyListener that listens everywhere inside a JDialog

 
Meyer Florian
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Meyer Florian
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic