问题
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