Saturday, 15 June 2013

java - How to accept a value in a Swing JComboBox with the Tab key -



java - How to accept a value in a Swing JComboBox with the Tab key -

how java combobox take highlighted value when type tab key, when type enter? think of ui norm, , have seen on websites , desktop programs, don't understand why java doesn't default. (the escape key there cancel.)

i found several related questions this, including how come in behave tab, turned out harder go other way, i'll post how did it. perhaps missed easy way!

in particular, the closest posting find didn't work because tab key consumed focus system. other related questions here , here, , maybe hints here.

this tricky because of how inaccessible enter-key handling is. takes place in big if-else tree in basiccomboboxui.actionperformed(). pulls value combobox also-inaccessible popup menu. it's tricky because focus-traversal key events consumed before can them.

to work, had remove tab set of focus-traversal keys, override processkeyevent() on jcombobox, , sorry! pass false enter-key event superclass, in order allow ui enter. had handle focus transitions manually.

here's code. (i handled shift-tab/backwards focus traversals same way, overkill.)

protected final jcombobox combobox = new jcombobox() { @override public void processkeyevent(keyevent e) { if ( e.getid() != keyevent.key_pressed || e.getkeycode() != keyevent.vk_tab) { super.processkeyevent(e); return; } if (ispopupvisible()) { assert e.getsource() instanceof component; keyevent fakeenterkeyevent = new keyevent((component) e.getsource(), e.getid(), e.getwhen(), 0, // no modifiers. keyevent.vk_enter, // come in key. keyevent.char_undefined); super.processkeyevent(fakeenterkeyevent); } if ( e.getmodifiers() == 0) { transferfocus(); } else if ( e.getmodifiers() == keyevent.shift_mask) { transferfocusbackward(); } } }; // remove tabs focus traversal keylists. // forward. set<awtkeystroke> focuskeys = sets.newhashset(combobox.getfocustraversalkeys(keyboardfocusmanager.forward_traversal_keys)); keystroke ltabkeystroke = keystroke.getkeystroke("pressed tab"); focuskeys.remove(ltabkeystroke); combobox.setfocustraversalkeys(keyboardfocusmanager.forward_traversal_keys, focuskeys); // backward. focuskeys = sets.newhashset(combobox.getfocustraversalkeys(keyboardfocusmanager.backward_traversal_keys)); keystroke lshifttabkeystroke = keystroke.getkeystroke("shift pressed tab"); focuskeys.remove(lshifttabkeystroke); combobox.setfocustraversalkeys(keyboardfocusmanager.backward_traversal_keys, focuskeys);

java swing focus jcombobox keylistener

No comments:

Post a Comment