Editable JComboBox: get current value when using shortcuts to start actions

103 views Asked by At

I've a problem to retrieve the current value in an editable JComboBox in a specific case: my application creates an editable JComboBox with a list of predefined texts, so that the user can either use one of the predefined texts or another text. Then he can click on buttons that will read the value in the JComboBox and will use this value to perform their action.

It works most of the time, but not in some situations: if the user types his text without pressing the Return key and then activate the button with a shortcut (Alt + ...), I get the previous value of the JComboBox and not the current one. If either the Return key is pressed or the button is activated by clicking on it, I get the correct value.

To read the value, I initially tried JComboBox.getSelectedItem().

I read the following topics on stackoverflow How to get value that has been written in editable JComboBox? and Get input values from JComboBox, so I tried JComboBox.getEditor().getItem() without seeing any difference.

I also read How can I know when the text of an editable JComboBox has been changed? and tried JComboBox.getEditor().getEditorComponent().toString(): nothing different.

Any idea ?

The shortcuts have been added to the buttons using their InputMap.

1

There are 1 answers

0
camickr On

The shortcuts have been added to the buttons using their InputMap.

Don't use the InputMap.

Instead you can set a mnemonic for the button. This will cause the button to gain focus when the mnemonic is invoked and therefore the combo box loses focus and the item is saved:

button.setMnemonic( KeyEvent.VK_1 );

so I tried JComboBox.getEditor().getItem() without seeing any difference.

This approach works for me. If the first suggestion doesn't help, then post your SSCCE showing your demo code.