Cg2916
Cg2916

Reputation: 1117

KeyListener Only Sometimes Works

I have made a Pong clone, and I've come across a problem. The KeyListener only works sometimes. There is no pattern that I have been able to find.

For reference here is my Pong.java(the main class): http://pastebin.com/8d7BqK4x

Here is the Board.java(Graphics and KeyListener): http://pastebin.com/0zb526BE

Upvotes: 1

Views: 1204

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Usually you don't want to use a KeyListener due to focus issues (which is likely why your listener only listens at times -- likely your listen-to component loses focus and so the KeyListener loses its function.

Better to use Key Bindings where you don't have to worry so much about focus issues and where you're dealing with a higher level construct, one that Swing uses itself to listen to components. The tutorials will "show you the way".

Upvotes: 2

camickr
camickr

Reputation: 324118

KeyEvents are only generated when a component has focus.

A better approach is to use Key Bindings which work even when the component doesn't have focus.

Upvotes: 3

Related Questions