aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes KeyListener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "KeyListener" Watch "KeyListener" New topic
Author

KeyListener

Tim Alvord
Greenhorn

Joined: Jan 24, 2013
Posts: 23
I have a JFrame to which I have added JButtons.



Where do I add the KeyListener to? win or c? I've tried both and the code never calls keyPressed(), keyReleased() or keyTyped()...

Any ideas on what I'm doing wrong?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39395
    
  28
Welcome to the Ranch

My, we have a lot of compiler errors in that code! Have you come across the Java Tutorials yet? I think that link will help you
I think the bit you have missed out is that you have to add the Listener to something.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39395
    
  28
Once I got rid of the many compiler errors, btnA.addKeyListener(this); seemed to do the trick. I had to click the button so it gained focus, then push a key.
Tim Alvord
Greenhorn

Joined: Jan 24, 2013
Posts: 23
Campbell,
If I attach the KeyListener to the button I have no problem. I need or would like anyway to attach it to the Frame or Container... I have alot of JButtons on the form and would rather not have to attach a KeyListener to all of them. I'd rather attach it to the Frame and then press the appropriate button...
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
KeyListeners will not work the you want them to.

KeyBindings is how you do it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39395
    
  28
…and this is where you can learn about key bindings.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: KeyListener