Responding to Button using KeyBIndings

前端 未结 2 437
别跟我提以往
别跟我提以往 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条回答
  •  一向
    一向 (楼主)
    2021-01-21 09:23

    you need to add an action listener, specificaly for actionPerformed. declare this somewhere inside your constructor:

    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.KeyStroke;
    
    public class Main {
        public static void main(String[] argv) throws Exception {
    
            JButton component = new JButton();
            MyAction action = new MyAction();
            component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
                action.getValue(Action.NAME));
        }
    }
    
    class MyAction extends AbstractAction {
        public MyAction() {
            super("my action");
        }
    
        public void actionPerformed(ActionEvent e) {
            //Here goes the code where the button does something
            System.out.println("hi");//In this case we print hi
        }
    }
    

    In this example if we press F2 it will be the equivalent of pressing the button.

提交回复
热议问题