My problem is when I click in the space of the frame screen it stops keyboard keys being registered so my player stop moving.
Thanks in advance for the help.
The code:
private Component comp;
....
public InputManager(Component comp) {
this.comp = comp;
mouseLocation = new Point();
centerLocation = new Point();
// register key and mouse listeners
comp.addKeyListener(this);
comp.addMouseListener(this);
comp.addMouseMotionListener(this);
comp.addMouseWheelListener(this);
// allow input of the TAB key and other keys normally
// used for focus traversal
comp.setFocusTraversalKeysEnabled(false);
}
GUI code:
Game game = new Game();
game.setMinimumSize(new Dimension(WIDTH * 2, HEIGHT * 2));
game.setPreferredSize(new Dimension(WIDTH * 2, HEIGHT * 2));
game.setMaximumSize(new Dimension(WIDTH * 2, HEIGHT * 2));
frame = new JFrame(Game.NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(game);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
I assume that you are using a KeyListener to listen for key input. Note that this will only work when the component being listened to have focus, and likely when you press the mouse on the JFrame, your listened to component loses focus.
The solution is not to use a KeyListener but instead use Key Bindings which are more robust than a KeyListener and a higher level concept.
Also, you’ll want to stop using this as your listener. If your program grows to be anything more than a toy program, it gets very hard to maintain a GUI class that uses itself as its own listeners.
Also, regarding: “oh yeah Game.java extends Canvas”: You don’t want to mix AWT and Swing components unnecessarily as this can cause side effects. Instead just use all Swing components such as JPanels instead of Canvases.