Combo Box pop up and select using keyboard shortcuts

给你一囗甜甜゛ 提交于 2019-12-11 09:19:26

问题


   public static void comboBoxActionPerform(JComboBox  comboBox)
    {
        String ACTION_KEY = "myAction";

        Action actionListener = new AbstractAction()
        {   
            @Override
            public void actionPerformed(ActionEvent actionEvent)
            {
                JComboBox source = (JComboBox) actionEvent.getSource();
                source.showPopup();
                source.setFocusable(true);
            }
        };

        KeyStroke ctrlT = KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK);
        InputMap inputMap = comboBox.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        inputMap.put(ctrlT, ACTION_KEY);
        ActionMap actionMap = comboBox.getActionMap();
        actionMap.put(ACTION_KEY, actionListener);
        locationTypeComboBox.setActionMap(actionMap);
    }

I have a com box and I call the above method to pop up combo box on keys (Ctrl+L) pressed. It pops up the combo box. But I can't select the items in it using UP/DOWN keys. Combo box get not focused when I pressed Ctrl+L. That might be the issue to be fixed. If I select the combo box manually and then up/down works fine. Need your help.


回答1:


The method you are looking for is requestFocus, not setFocusable

    Action actionListener = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            JComboBox source = (JComboBox) actionEvent.getSource();
            source.requestFocus();
            source.showPopup();
            // source.setFocusable(true);
        }
    };

BTW, it's unusual to reset the actionMap of a component.



来源:https://stackoverflow.com/questions/12363990/combo-box-pop-up-and-select-using-keyboard-shortcuts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!