• Post Reply Bookmark Topic Watch Topic
  • New Topic

using keypress event in cardlayout not working as expected  RSS feed

 
rodolfo tuble
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I've read that to enable keypress event you need to setfocus on the panel where the event will be placed thus I have this:



As you can see I am using cardlayout and have multiple JPanels, card17 and card11 are just a few of them.

Then I added a keypress event on both card17 and card11 resulting to this:



But neither of them are working as I can't get them to print anything. Also I wanted to try something like this:



I got it from here but netbeans gives me an error in getActionMap and getInputMap saying that I should create a method for them which I'm not sure how to, thus I opted not to continue with it and return to the classic event trigger.

Any help is greatly appreciated.
 
Les Morgan
Rancher
Posts: 768
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You KeyListener has to implement the KeyListener interface.
 
Fred Kleinschmidt
Bartender
Posts: 560
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your Stuff() constructor you request focus for card17, then two lines later you request focus for card11. Make up your mind which one you want to have focus.

But if these are components in a JPanel using CardLayout, these calls are useless; the CardLayout will display its active component and give focus to that component.

You say you
added a keypress event on both card17 and card11
. You don't add an event to a component - you add an event listener. You don't show any code for doing that.
 
Rob Camick
Ranch Hand
Posts: 2801
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but netbeans gives me an error in getActionMap and getInputMap saying that I should create a method for them which I'm not sure how to


Well, fix your code. This is the proper solution.

There are plenty of examples on the internet that use "Key Bindings". All you need to do is search for any example using ActionMap and InputMap.

You can start by reading the Swing tutorial on How to Use Key Bindings where you will find more information and working code you can download.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!