开发者

Java - JPanel and KeyListener Problem

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 Dime开发者_Python百科nsion(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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜