Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to add the respective key to the <code>InputMap</code> of the component on which to apply <code>KeyBinding</code> as shown here : </p> <pre><code>panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke("pressed UP"), "pressedUPAction"); panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke("released UP"), "releasedUPAction"); panel.getActionMap().put("pressedUPAction", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { System.out.println("UP Arrow Pressed"); } }); panel.getActionMap().put("releasedUPAction", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { System.out.println("UP Arrow Released"); } }); </code></pre> <p>Have a look at this working example :</p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SmallExample { private JButton button; private JPanel panel; private void displayGUI() { JFrame frame = new JFrame("Small Example"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); panel = new JPanel() { @Override public Dimension getPreferredSize() { return (new Dimension(100, 100)); } }; panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke("pressed UP"), "pressedUPAction"); panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke("released UP"), "releasedUPAction"); panel.getActionMap().put("pressedUPAction", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { System.out.println("UP Arrow Pressed"); } }); panel.getActionMap().put("releasedUPAction", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { System.out.println("UP Arrow Released"); } }); frame.setContentPane(panel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { new SmallExample().displayGUI(); } }; EventQueue.invokeLater(runnable); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload