KeyListeners not working
Hello everyone, I'm kind of a newbie to the swing interface, and this is my first post in the java forums. So, I apologize if I'm making a very stupid/obvious mistake.
My project set up right now has a Jframe, a custom class that extends Jcomponent, and a TextArea. My custom Jcomponent implements KeyListener, and uses the keyPress function as part of its purpose. When I have just the JComponent in the JFrame, the key events (as well as mouse and timer events) work fine. But when I add the textarea to the frame, the keylisten events (but not the mouse or timer events) stop being called.
My first thought was that my component wasnt in focus. So for testing I disabled focusing on my TextArea, and made my custom class constantly calling the requestFocus() function. Debugging revealed that this was succesful, and that the currently focused object was always my jcomponent. But still, the keyboard events didnt work!
Does anyone know what could be causing this, or what I can do to fix this? Thank you for your help!
If at all possible, you'll be better off using Key Bindings rather than a KeyListener, and there's a great tutorial on this at the Java Swing tutorials.
Those are really interesting actually. I like the idea of having actions; feels like it would be a lot cleaner than a bunch of esoteric conditionals. Thanks a bunch! :)
I haven't done much playing around with them yet, but I think it can handle most of what I'm trying to do.
Although I'm still curious as to what I'm doing wrong with keyListeners/focus, if anyone has any ideas. :/
A problem may be that your component is not focusable, that is, it's focusable property is false, and if so, even if you request the focus, it isn't able to obtain it. You can change this by calling setFocusable(true) on the JComponent.