2

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();
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
DCSoft
  • 217
  • 1
  • 4
  • 17

1 Answers1

9

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 2
    +1 for Key Bindings. +1 for stop using this as listener and +1 for mixing remark. Hmm, do I need to upvote two other posts to give you your credit ? – Robin Aug 03 '12 at 22:07
  • Thank you, this helped alot. I will definitely try the Key Bindings. – DCSoft Aug 03 '12 at 22:34
  • I have found a temporary solution, I've passed the game class into the InputManager class instead of the JFrame. – DCSoft Aug 03 '12 at 22:50