Responding to Button using KeyBIndings

前端 未结 2 434
别跟我提以往
别跟我提以往 2021-01-21 09:13

I want to make a program with these goals:

1) Make a JButton 2) Attach the button to a key (The \"A\" Key) using KeyBindings 3) Execute some code when \"A\" is clicked

2条回答
  •  -上瘾入骨i
    2021-01-21 09:39

    Two ways I can think of:

    • Have JButton and and Key Bindings share the same AbstractAction, or perhaps better
    • Simply call doClick() on the button from the key binding.

    KeyBindingEg.java

    import java.awt.event.*;
    import javax.swing.*;
    
    public class KeyBindingEg extends JPanel {
       private JButton btnA = new JButton();
    
       public KeyBindingEg() {
          Action btnAction = new ActionOne("A");
          Action keyBindingAction = new ActionTwo();
    
          int condition = JLabel.WHEN_IN_FOCUSED_WINDOW;
          InputMap inputmap = btnA.getInputMap(condition);
          ActionMap actionmap = btnA.getActionMap();
    
          final String aKeyPressed = "a key pressed";
          inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), aKeyPressed );
    
          actionmap.put(aKeyPressed, keyBindingAction);
          // actionmap.put(aKeyPressed, btnAction); // one or the other, your choice
    
          btnA.setAction(btnAction);
          add(btnA);
       }
    
       private class ActionOne extends AbstractAction {
          public ActionOne(String text) {
             super(text);
          }
    
          @Override
          public void actionPerformed(ActionEvent e) {
             sharedMethod();
          }
       }
    
       private class ActionTwo extends AbstractAction {
          @Override
          public void actionPerformed(ActionEvent e) {
             btnA.doClick();
          }
       }
    
       private void sharedMethod() {
          System.out.println("Method called by either key bindings or action listener");
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("KeyBindingEg");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new KeyBindingEg());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    

提交回复
热议问题