create hot keys for JButton in java using swing

后端 未结 4 1539
长发绾君心
长发绾君心 2020-12-03 15:51

I use the following code to create hot keys for the java form using swing. If I press ALT+N,ALT+R,ALT+1,ALT+2 the cursor moves to correct text fields and I enter the value i

4条回答
  •  广开言路
    2020-12-03 16:37

    You need to register a keyBinding in the button's component inputmap. In code (repeating a subtle variant of what you have been told to do in your previous questions :-)

    // create an Action doing what you want
    Action action = new AbstractAction("doSomething") {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("triggered the action");
        }
    
    };
    // configure the Action with the accelerator (aka: short cut)
    action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));
    
    // create a button, configured with the Action
    JButton toolBarButton = new JButton(action);
    // manually register the accelerator in the button's component input map
    toolBarButton.getActionMap().put("myAction", action);
    toolBarButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
            (KeyStroke) action.getValue(Action.ACCELERATOR_KEY), "myAction");
    

提交回复
热议问题