For reference, I am creating an example using your approach; while it works, it also offers a focus problem elsewhere in your code. Key Bindings avoid this, as shown here .
Addendum: Here is my working key binding.
private static class TestPanel extends JPanel { private static final String LEFT = "Left"; private Action left = new AbstractAction(LEFT) { @Override public void actionPerformed(ActionEvent e) { System.out.println(LEFT); } }; private static final String RIGHT = "Right"; private Action right = new AbstractAction(RIGHT) { @Override public void actionPerformed(ActionEvent e) { System.out.println(RIGHT); } }; public TestPanel() { this.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), LEFT); this.getActionMap().put(LEFT, left); this.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), RIGHT); this.getActionMap().put(RIGHT, right); } }
Original SSCCE:
import java.awt.EventQueue; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JPanel; public class Test { private void display() { JFrame f = new JFrame("Test"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new TestPanel()); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } private static class TestPanel extends JPanel implements KeyListener { public TestPanel() { this.addKeyListener(this); this.setFocusable(true); this.requestFocusInWindow(); } @Override 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"); } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new Test().display(); } }); } }
source share