Registring a KeyPress event on a JPanel
Hey,
I have a class that extends JPanel, added it to the Palette, and dragged it on a 'window' (class that extends JFrame).
All I want to do is handle a KeyPress event, but it's not working.
I simply went into Design view, selected the JPanel, went into the Events tab and added a keyPressed event handler.
I added some code in the handler, but a breakpoint verifies that the code is never hit: the event is never raised it seems.
Now, I have very little GUI experience with Java (read: very little experience with Java), but I'm used to .NET (VB/C#) where I can simply select an event and it will add the appropriate code automatically (in VB: the Handles clause behind the event handler method; in C#: adding an event handler method in the designer code), and as far as I can see Java works the same, because in the designer generated code I see this:
Code:
panel.setPreferredSize(new java.awt.Dimension(960, 660));
panel.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
panelKeyPressed(evt);
}
});
(panel is the JPanel I added)
But, as I said, the event handler method is not hit.
What am I doing wrong? Is there something fundamentally different in Java that I'm not getting, or can a JPanel simply not receive keypress events? In the last case, I also tried handling the key presses on the window ('form') directly, with the same result: nothing.
Thanks for any help!
Re: Registring a KeyPress event on a JPanel
Well, the panel must have focus in order to catch the Key press event.
Re: Registring a KeyPress event on a JPanel
Can a panel receive focus? And even if it can, there are also a few buttons on the window, so I cannot guarantee that the panel has focus. Can't I catch the key press event of the entire window instead? Or will that not work if some other control has focus?
Simply put: the panel is drawing a game, and I need to control the game with the arrow keys. That can't be too hard, can it?
Re: Registring a KeyPress event on a JPanel
Try calling panel.requestFocus(); on game start
Re: Registring a KeyPress event on a JPanel
Thanks, that seems to work. What happens if I click a button in the middle of the game though, I suppose the focus is then lost and I need to re-set it or something? (The buttons aren't there yet so I haven't tried)
Re: Registring a KeyPress event on a JPanel
You'll need to call the same method at the end of every button click event handler