I am just starting to learn JavaFX 2.
Now I am trying to build a sample application. Then I got stuck in combobox.
I did not find any reference to key value pair for combobox in JavaFX.
The combobox javadoc at http://docs.oracle.com/javafx/2/api/index.html does not say much about key value pair.
How can I create a combobox that has items which have different display value and actual value ?
You have 2 approaches:
1. Simply override the
toString()
method in your datamodel class. Example:Note the overriden toString() of the Employee class. The combobox's key (actual value) will be the
Employee
instance and the display value isemployee.toString()
in this case.2. Second approach is to set cellFactory property of the combobox.
This approach gives more powerful control over cell rendering. You can not just format display value but also include any node (control) into cell (button in this case) and add some viewing logic (item.getSalary()?"":"") too. The actual value remains the same ie Employee instance.
I know that this question is old, but because I just spent hours in pointless digging on this issue it's a kind of mandatory for me to share the results. It seems that the ComboBox with overriden toString() method resolves the strings back to objects just right even if there are string duplicates in the list. The resolution must be index based and toString() is used only for presentation.
There is another solution, implementing a StringConverter. It's very useful for objects:
Converter implementation:
Code in view:
To get the value of the product, you can call getValue() method: