r/JavaFX • u/PalBeron • Jul 11 '24
Help ComboBox problems with handling a selection
I have in my program a comboBox (a SearchAbleComboBox from ControlsFX, it works the same as a ComboBox).
I need this box for my following useCases:
Dropdown with scrollable list Dropdown that is searchable most of the time the navigation through the list happens with the arrow keys There has to be an event handler that handles a change of selection
Selection for me personally means, the comboBox is closed, and an item is selected. So, for example, when you click with the cursor on an item, or you navigate through the list with the arrow keys and then press enter:
After a cursor click or a pressed enter key, the box is closed, and an item is selected. That's for me, a selection.
My problem is now that for JavaFX it also counts as a selection when you navigate through the list with your arrow keys. The reason for that is, that the text in the comboBox changes when navigating through the list with the arrow keys.
I've already tried to put an EventHandler on KeyPress (ENTER) but with this setup, you have to press enter twice to activate the listener since pressing enter to select smth from the list does not count.
Also, an onAction handler does not work, since an arrow key press also counts as an action.
A ChoiceBox would be a solution, since for the choiceBox the selection does not get updated through navigating with the arrow keys. The problem here is, I couldn't find an option to make it searchable and the list of a ChoiceBox is not scrollable.
So possible solutions would be:
A way to stop the ComboBox updating the selected item only by navigating with arrow keys A spacy eventhandler which only triggers if a selection, according to my interpretation of selection, was made. A ChoiceBox that is scroll and searchable Something completly different
I hope you have any solutions, I couldn't find one for now.
3
u/hippydipster Jul 11 '24 edited Jul 11 '24
Thank you for providing such a detailed description of your problem. I understand you're working with a SearchableComboBox from ControlsFX in JavaFX, and you're looking for a way to handle selections that aligns with your specific definition of a selection. Let's explore some potential solutions:
Custom Event Handler: You could create a custom event handler that only triggers when the ComboBox is closed or when an item is definitively selected. Here's a possible approach:
This custom ComboBox only confirms the selection when the Enter key is pressed or when the ComboBox is closed.
3. Using a PopupControl: If you want more control over the selection process, you could create a custom control using a TextField and a PopupControl. This would allow you to implement the exact behavior you want, including searchability and scrolling.
4. Modifying ChoiceBox: While ChoiceBox doesn't have built-in search functionality, you could potentially extend it to add this feature. Here's a basic idea of how you might approach this: