views:

34

answers:

1

I have a JFrame with 3 panels. I extend an App class, and then add three panels to it, like so:

JPanel controlButtonsPanel = new GameControlButtons();
        controlButtonsPanel.setPreferredSize(new Dimension(801,60));
        controlButtonsPanel.setBorder(new LineBorder(Color.white, 1));
        constraints.anchor = GridBagConstraints.NORTHWEST;
        constraints.weightx = 2;
        constraints.weighty = 0.3;
        this.add(controlButtonsPanel, constraints);

        JPanel tempP = new JPanel();     
/`/ *** I'm going to create a Jpanel subclass for this, too, I just haven't yet.`
        tempP.setPreferredSize(new Dimension(500,838));
        tempP.setBorder(new LineBorder(Color.white, 2));
        constraints.anchor = GridBagConstraints.NORTHEAST;
        constraints.weightx = 1;
        constraints.weighty = 2;
        this.add(tempP, constraints);

        JPanel graphicsPanel = new RoofRunnerGame("Ken");
        constraints.anchor = GridBagConstraints.SOUTHWEST;
        constraints.weightx = 2;
        constraints.weighty = 1;
        graphicsPanel.setBorder(new LineBorder(Color.white, 1));
        graphicsPanel.setPreferredSize(new Dimension(800,800));
        graphicsPanel.requestFocus();
        this.add(graphicsPanel, constraints);       

I've extended JPanel for the GameControlButtons and RoofRunnerGame classes. I've added a mouselistener to the former. And I've add a mouse listener and a key listener to the latter.

** The problem: the mouse listeners work fine for both, but the key listener does't seem to listen in my RoofRunnerGame panel.**

I found two possible fixes online, but wanted to ask first.

1) One was calling requestFocus() in the RoofRunnerGame subclass. The problem with this is that once I clicked a different panel, it loses focus. (It's a short term fix.)

2) Another thing mentioned was to use keyBindings. I have never used them before. I will if you recommend it, but would prefer to keep using keyListener if that's possible.

So, what do you think? Is there some way I can keep the RoofRunnerGame panel to KEY listen throughout?

A: 

You can make other panels not focusable, but it might also require making every component on those panels not focusable.

See this, and this examples about adding a key listener through ActionMap. JComponent.WHEN_IN_FOCUSED_WINDOW flag in getInputMap() method should allow your panel to receive input events even when it's not focused.

tulskiy
What about Key Bindings? When and why are they used? Are they superior to keyListeners in this case??
Dan James
@Dan James: Examples I gave are about key bindings. They're better because they make better use of actions (you can reuse same action for buttons, menu items), you can specify when a component should receive an input event (when it's focused or whenever it's in a focused window) etc. They're a higher level of abstraction than key listeners.
tulskiy