我正在尝试使用我的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) {}
}
Run Code Online (Sandbox Code Playgroud)
我的main方法将一个新面板实例添加到一个框架并显示它.我需要将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"); …Run Code Online (Sandbox Code Playgroud)