gpt4 book ai didi

java - Keylistener 不适用于 JPanel

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:52 25 4
gpt4 key购买 nike

当使用我的 JPanel 类中的 KeyListener 按下其中一个箭头键时,我正在尝试做一些事情。这是我的代码:

public class TestPanel extends JPanel implements KeyListener{

public TestPanel(){
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
}

public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right");

}

if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left");
}

}

public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}

我的主要方法将这个面板的一个新实例添加到一个框架中并显示它。我需要将 keylistener 添加到 JFrame 吗?在我的例子中,这将是困难且低效的,所以如果可能的话,我想让它与这个 JPanel 一起工作。有人知道我做错了什么吗?

编辑:键绑定(bind)代码也不起作用:

public class GamePanel extends JPanel implements ActionListener{

//Constructor
public GamePanel(){

setupKeyBinding();
this.setFocusable(true);
this.requestFocusInWindow();


}

private void setupKeyBinding() {
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inMap = getInputMap(condition);
ActionMap actMap = getActionMap();

inMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
actMap.put("Left", new leftAction());
}

private class leftAction extends AbstractAction {

public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
}

public void actionPerformed(ActionEvent e) {
//some other game info
}
}

有人能告诉我为什么这也不起作用吗? (我的第二个 Action 监听器用于我的游戏所需的其他内容)

最佳答案

如果你搜索这个问题,你会发现它被问过很多次并且已经解决了很多次。

  • KeyListeners 需要在焦点组件上才能工作。一种解决方案是在首先使其可聚焦后为您的组件提供焦点。
  • 不过,从长远来看更好的方法是使用键绑定(bind)。 Google 教程。

请看我对this question的回答有关更多信息,包括许多血淋淋的细节。

关于java - Keylistener 不适用于 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16530775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com