Reputation: 1864
I'm having issues wrapping my head around what getValue()
actually returns, or rather: Eclipse seems to have that issue. This is my ComboBox:
ComboBox<Integer> intBox = new ComboBox<Integer>;
ObservableList<Integer> intList = FXCollections.observableArrayList();
I fill the ComboBox
with Integers from intList
by doing:
intBox.getItems().addAll(intList);
And I also set the ComboBox
to editable by doing setEditable(true)
.
The problem is that if I try to store the value of intBox.getValue()
in an Integer
or int
variable, I get "java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer" during runtime". But if I try to store it into a String
instead, Eclipse gives me the compile error: "Type mismatch: cannot convert from Integer
to String". So the compiler tells me its an Integer, but I still can't store it in an Integer, why?
I've also tried various workarounds, like Integer.parseInt
, getValue().intValue()
and Integer.toString()
, and storing those values in various variables of different datatypes, but they've all given me the same or similar errors.
Upvotes: 3
Views: 1172
Reputation: 209358
From the documentation:
Because a ComboBox can be editable, and the default means of allowing user input is via a TextField, a string converter property is provided to allow for developers to specify how to translate a users string into an object of type T, such that the value property may contain it. By default the converter simply returns the String input as the user typed it, which therefore assumes that the type of the editable ComboBox is String. If a different type is specified and the ComboBox is to be editable, it is necessary to specify a custom StringConverter.
Basically, if the ComboBox
is editable, it will get its value from the editor (a TextField
), which supplies a String
. If you have an editable combo box whose type is not String
, you need to supply a way to convert the string from the text field to the value of the appropriate type, and vice-versa. So you need
intBox.setConverter(new IntegerStringConverter());
Upvotes: 4