简体   繁体   中英

Key Bindings for complex gui

I am trying to get my application to respond to keyboard input. Eventually, I would like it to register ctrl+f and initiate a search, but I started simple and tried for the space bar. The Java tutorials on using Key Bindings got me this far, but no matter what I apply the key binding to, nothing registers. In the below code, panel is a JPanel and the others are assorted swing objects which have been added to panel.

    Action ctrlF = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
           System.out.println("Action performed");
        }
    };
    panel.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");
    openStallsList.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");
    openStalls.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");
    stallScroller.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");
    assignLabel.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");
    tenantInfo.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");
    unitSpinner.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");
    buildingAddress.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");
    buildingLogo.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"crtlF");

What am I missing here? Does it have something to do with focus? There are a couple of assorted labels and buttons which are not included on that list. Is there any way to get panel to register all of the input from all of it's children?

Thanks

First, you need bind a KeyStroke to some kind of "key". Now personally, it's eaiser to specifiy the virtual key then using a String , as the String value can be a little temperamental, but that's me

panel.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),"crtlF");

Next, you need to bind the "key" to an Action

panel.getActionMap().put("crtlF", ctrlF);

See How to use key bindings for more details.

The next problem you will have is the component will need to be focused before the key binding can be triggered

You could try and get the InputMap with a different focus requirement using either WHEN_ANCESTOR_OF_FOCUSED_COMPONENT or WHEN_IN_FOCUSED_WINDOW which will allow you to change the focus level required by the component in order for the key binding to be triggered.

ie,

int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = panel.getInputMap(condition);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),"crtlF");
//... etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM