Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

KeyListener

 
Tim Alvord
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
KeyListeners will not work the you want them to.

KeyBindings is how you do it.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
…and this is where you can learn about key bindings.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic