我想在JPanel類中使用KeyListener按下其中一個箭頭鍵時執行某些操作。這裏是我的代碼:Keylistener不適用於JPanel
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一起工作。任何人都知道我在做什麼錯了?
編輯:鍵綁定的代碼無法正常工作或:
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
}
}
誰能告訴我,爲什麼這不工作要麼? (我的第二個動作偵聽器是爲我的遊戲需要的其他東西)
另一個想法可能是製作一個內部類,並使用類似於:「this.addKeyListener(內部類/匿名內部類);」 – ObedMarsh 2013-05-13 21:00:10
可能重複的[java keylistener not called](http://stackoverflow.com/questions/8482268/java-keylistener-not-called) – 2013-05-13 21:17:45