Question

In my current project, I am using AutoCompleteDecorate from SwingX. AutoCompleteDecorator.decorate(jComboBox1);

However, I want to override the backspace action. Originally, using AutoCompleteDecorate.decorate(JComboBox), pressing backspace move the selection in combobox to the left and doesn't delete the previous character. I want to implement the default function of backspace (which is to delete previous character) even if I AutoCompleteDecorate my JComboBox.

Please help me solve my problem. Thank you in advance.

Was it helpful?

Solution

Not trivial - the decorator goes a long way to implement the select-instead-of-delete ;-)

First you need to define which behaviour you want. Then implement a Action that does as you intend and place it in the editor's ActionMap:

Action myBackspace = ...
ActionMap map = ((JComponent) decorateCombo.getEditor().getEditorComponent())
     .getActionMap();
map.put("nonstrict-backspace", myBackspace);

This is vague because because I can't know what exactly you want, best to look at the source of AutoComplete to get an idea of how to implement myBackspace

Edit

Just to elaborate a bit on the vagueness: my first thought was to simply re-install the default backspace binding like:

InputMap map = ((JComponent) decorateCombo.getEditor().getEditorComponent())
    .getInputMap();
map.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_BACK_SPACE, 0), 
            DefaultEditorKit.deletePrevCharAction);

that's most probably not what is expected: assuming the caret is somewhere in the middle of a contained element in an editable combo, then the text from the caret to the end is selected, consequently the deletePrev deletes the selected not the prev char. Which might lead the way to implement the custom action: first clear the selection, then deletePrev, then check if the new word is in the list and re-select (or not). Hard to tell without knowing the requirement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top