fubarable

Key Bindings Example

Jul 4th, 2016
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. import java.awt.event.ActionEvent;
  2. import java.awt.event.KeyEvent;
  3. import javax.swing.*;
  4.  
  5. public class KeyBindingTest extends JPanel {
  6.     public KeyBindingTest() {
  7.         initializeKeyBinds();
  8.     }
  9.  
  10.     void initializeKeyBinds() {
  11.         Action timerAction = new DoAction();
  12.         System.out.println("Here at initializeKeyBinds");
  13.         InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
  14.         ActionMap am = getActionMap();
  15.         im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "SPACE");
  16.         am.put("SPACE", timerAction);
  17.     }
  18.  
  19.     static class DoAction extends AbstractAction {
  20.         @Override
  21.         public void actionPerformed(ActionEvent tf) {
  22.             System.out.println("The Enter key has been pressed.");
  23.             // scrambleButton.doClick();
  24.         }
  25.     }
  26.  
  27.     private static void createAndShowGui() {
  28.         KeyBindingTest mainPanel = new KeyBindingTest();
  29.         JFrame frame = new JFrame("KeyBindingTest");
  30.         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  31.         frame.getContentPane().add(mainPanel);
  32.         frame.pack();
  33.         frame.setLocationByPlatform(true);
  34.         frame.setVisible(true);
  35.     }
  36.  
  37.     public static void main(String[] args) {
  38.         SwingUtilities.invokeLater(() -> createAndShowGui());
  39.     }
  40. }
Add Comment
Please, Sign In to add comment