Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 Android Security Essentials Live Lessons this week in the Android 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: 38062
    
  22
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: 38062
    
  22
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: 38062
    
  22
…and this is where you can learn about key bindings.
 
Don't get me started about those stupid light bulbs.
 
subject: KeyListener
 
Similar Threads
Custom Button Problem
Error message Lat1 isn't abstract method
Add 2D shape to 2D shape and move the first one. Both should move.
SWING GUI ADVICE,PLEASE
SWING GUI ADVICE,PLEASE