If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

Issues with listeners in a snake game

I'm very new to this, trying to make a snake game and I'm having a bit of difficulty getting the directional buttons to do what I want. At the moment I am just trying to get a square to move in the direction of the last arrow key by changing the dx and dy values that a move() method uses. It changes those values by the setMove(int i, int i) method until you press the start button which starts the timer which calls move() on the block, then for some reason the keystrokes don't even register.

I suspect it might be an issue with multiple listeners (and different types) or something to do with the setFocusable(boolean b) method that perhaps needs to be called again at some stage?

I realise this is a slightly convoluted way to set out the panels and JFrame but I have extended this from a class project. It's not a class project but it just uses some of the layout from one I have finished already.

Any help would be appreciated even just tips for debugging or ideas why this might not be working.

Looks to me that its simply a problem with the focus.
There are a few fixes, one would involve setting the keyListener on the frame itself, and another would simply be requesting it back. In the ButtonListener, simply add requestFocus(); as the final instruction in the actionPerformed. That will pass it back to the SnakePanel.

Looks to me that its simply a problem with the focus.
There are a few fixes, one would involve setting the keyListener on the frame itself, and another would simply be requesting it back. In the ButtonListener, simply add requestFocus(); as the final instruction in the actionPerformed. That will pass it back to the SnakePanel.

Thank you very much Fou-Lou, it works now! I had done a bit of looking around and thought it might be a simple fix but simply don't know enough about focus myself (first time I've come across it). Cheers!