Ahmad Hoghooghi
Ahmad Hoghooghi

Reputation: 155

JavaFX ChoiceBox EventHandling

I'm trying to detect ChoiceBox item selection. I read this post and I know that it is possible to do, this way:

choiceBoxObject.getSelectionModel().selectedIndexProperty().addListener(myChangeListenerObject)

also I saw this sentence in Documentation for ChoiceBox class which confirms code above:

ChoiceBox item selection is handled by SelectionModel As with ListView and ComboBox

Another solution came to my mind and I was wondering is there anything wrong with it? why nobody mentioned this way? What is the difference between these two approaches?

choiceBoxObject.valueProperty().addListener(myChangeListenerObject);

Upvotes: 0

Views: 200

Answers (1)

James_D
James_D

Reputation: 209428

There's nothing wrong with using the valueProperty, and in fact for simply reacting to changes in the selected value, it's probably the preferred solution.

The documentation is just indicating that there is a complete SelectionModel underlying the selection of items. This has a far richer API than simply knowing what is selected: there are selectNext(), selectFirst() methods, etc etc. So if you needed to programmatically change the selection there is a rich API available. As also pointed out in the documentation, you can even replace the selection model with a different implementation, though use cases for this are likely to be (very) rare.

Upvotes: 0

Related Questions