I have an application that is set up like this, the main frame is a jframe, I have a menu bar on it and two jpanels on the inside of the jframe, one to hold the textfields and one to hold my buttons, previous and next. I want to add keylisteners to the application so that when you press the right arrow key it would be the same as pressing the next button and the left arrow key the same as the Previous button. What part of my app (the jframe, the buttons or the jpanels) should I add the keylisteners too?? I think I've tried them all, but it seems like it does nothing do I have to do something else since I have so many panels, add a focus to one of them, or maybe the buttons?? Any help here would be appriciated. Thank you for your time and GOD Bless.
Well, here is the problem. There is no such thing as a Global KeyListener in Java. The only way to handle this is to add a KeyListener to every single component in your JFrame so that every component is listening for KeyEvents.
This is a lot easier than it sounds, luckily. Take a look at this JavaWorld article for a really good and simple example.
I did some testing with it and it worked great. Something else I didn't know before reading that article and testing that is helpful is that the Arrow Keys don't register keyTyped events. Only keyPressed and keyReleased so make sure your code that handles those events are in the right KeyListener methods.
In whatever code initializes the JButtons (Next, previous, etc.) you should be able to do something like this:
I've found that KeyListener's are appropriate for situations when you want to be able to handle arbitrary input, like if you're writing a text component that accepts characters of any kind. Much more commonly I use InputMaps, which are there to handle binding a specific key to an action and can easily watch all keystrokes sent to the window or to sub-components of a parent component. Check out How to Use Key Bindings in the Java Tutorial for more info.