0

For school I have to make a small game which is based on Breakout.

I got my JFrame which does this:

game.setFocusable(true);
setContentpane(game);

in my game I am adding a inputhandler which extends Keylistener and implements JPanel.

setFocusable(true);
Inputhandler input = new Inputhandler();
addKeylistener(input);

It just doesn't seem to work, I've been writing a lot of tests but I can't see to get the input handle capture any keyPressed.

When I change my JFrame to:

add(game);

it works like it is meant to work but the problem I encounter when doing this way is painting my panels the correct way. I'm kinda stuck on this issue so please someone help me out.

Point I've reached now:

public Game(){
    setFocusable(true);
    requestFocus();
    requestFocusInWindow();

    getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "pressed");
    getActionMap().put("pressed", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Space is pressed");
        }
    });

    this.inputHandler = new InputHandler();
    addKeyListener(this.inputHandler);

    setPreferredSize(new Dimension(500,500));
}
Giani Noyez
  • 481
  • 3
  • 8
  • 17

1 Answers1

3

If I had a dollar for every time this question were asked, I'd retire rich. As per previous similar questions...

  • Yes you would need to make the JPanel focusable for its KeyListener to work
  • And you'd also have to give it the focus, since being focusable is not enough. Usually this is achieved by calling requestFocusInWindow() on the listened to JPanel.
  • And nothing else can have the focus or steal the focus if the KeyListener is to continue functioning.
  • Which is one of several reasons why most of us recommend against use of KeyListeners for Swing applications
  • And usually in favor of using Key Bindings.

Edit

I've used your code and it works, both the key bindings and the KeyListener:

import java.awt.Dimension;
import java.awt.event.*;

import javax.swing.*;

public class Game extends JPanel {
   private InputHandler inputHandler;

   public Game() {
      setFocusable(true);
      requestFocus();
      requestFocusInWindow();
      getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "pressed");
      getActionMap().put("pressed", new AbstractAction() {
         @Override
         public void actionPerformed(ActionEvent e) {
            System.out.println("Space is pressed");
         }
      });
      this.inputHandler = new InputHandler();
      addKeyListener(this.inputHandler);
      setPreferredSize(new Dimension(500, 500));
   }

   class InputHandler extends KeyAdapter {
      @Override
      public void keyPressed(KeyEvent e) {
         System.out.println("key pressed");
      }

      @Override
      public void keyReleased(KeyEvent e) {
         System.out.println("key released");
      }
   }

   private static void createAndShowGui() {
      Game mainPanel = new Game();

      JFrame frame = new JFrame("Game");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I wouldn't be asking if the search would've given me any answer that would suffice for my case. I will check if every condition that you've given me is fulfilled and I will report back to you. – Giani Noyez Nov 30 '14 at 00:58
  • 1
    `"I wouldn't be asking if the search would've given me any answer that would suffice for my case."` your question makes no mention of your Key Bindings attempt. And you will likely never find an answer or tutorial that is specific for your exact case, but you will likely find answers that are generally applicable to portions of your problem, and then it will be up to you to synthesize a solution from the sources. – Hovercraft Full Of Eels Nov 30 '14 at 00:59
  • I'm not using keybindings. I'm just adding this to the Keypressed of Keylistener: System.out.println("Key is pressed); – Giani Noyez Nov 30 '14 at 01:06
  • 1
    @GianiNoyez: I would suggest that you in fact consider using Key Bindings. If you've done a large search of this site on similar questions, you'll likely have seen this recommendation. Note that for better and more complete help, consider creating and posting a [minimal example program](http://stackoverflow.com/help/mcve), a small but complete program that only has necessary code to demonstrate your problem, that we can copy, paste, compile and run without modification. – Hovercraft Full Of Eels Nov 30 '14 at 01:09
  • I now got this in my testing project public Game(){ setFocusable(true); requestFocus(); requestFocusInWindow(); getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "pressed"); getActionMap().put("pressed", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Space is pressed"); } }); this.inputHandler = new InputHandler(); addKeyListener(this.inputHandler); setPreferredSize(new Dimension(500,500)); } It's not doing anyt – Giani Noyez Nov 30 '14 at 01:16
  • @GianiNoyez: Please don't post code in comments since it loses its formatting making it unreadable. Instead, post any new code to the bottom of your original question by [editing your question](http://stackoverflow.com/posts/27208846/edit) (check out the link). – Hovercraft Full Of Eels Nov 30 '14 at 01:18
  • Okay thanks.. I understand what you did but I don't understand why my way of approaching it doesn't work. – Giani Noyez Nov 30 '14 at 01:26
  • 1
    @GianiNoyez: there's a big difference between the code you've posted and the code I've posted. Anyone can run and test my code unmodified to see if it is correct. The same cannot be said of yours because it does not yet conform to the [mcve](http://stackoverflow.com/help/mcve) standard. Again, the best way to get us to understand why your code is not working, is for you to post a small example program that **shows** us. Note that my code **is** your code, only that it runs and runs correctly, and so I can only assume that you've a bug in code not yet shown. – Hovercraft Full Of Eels Nov 30 '14 at 01:27
  • Okay, I've been playing around with your code, implemented your code into mine and it seems to be working. Sorry about the MCVE standard, I'm still getting used to it. I will get it right in the future when I'm not this desperate. Thanks for your patience and all the work you've done to help me! You have helped me a lot! – Giani Noyez Nov 30 '14 at 01:34