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?