我有一个带有3个面板的JFrame。我扩展了一个App类,然后向它添加了三个面板,如下所示:
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);
我为GameControlButtons和RoofRunnerGame类扩展了JPanel。我给前者添加了一个mouselistener。我为后者添加了一个鼠标监听器和一个关键监听器。
**问题:鼠标监听器都可以正常工作,但是关键监听器似乎没有在我的RoofRunnerGame面板中监听。**
我在网上找到了两个可能的修复程序,但是想先问一下。
1)一个人在RoofRunnerGame子类中调用requestFocus()。这个问题是,一旦我点击了另一个面板,它就会失去焦点。 (这是一个短期修复。)
2)提到的另一件事是使用keyBindings。我以前从未使用过它们。如果你推荐它我会,但如果可能的话,我宁愿继续使用keyListener。
所以,您怎么看?有什么方法可以让RoofRunnerGame面板始终保持KEY监听吗?