可编辑的 ComboBox:getValue() 的问题

editable ComboBox: issues with getValue()

我在思考 getValue() 实际上 returns 的问题时遇到了问题,或者更确切地说:Eclipse 似乎有这个问题。这是我的组合框:

ComboBox<Integer> intBox = new ComboBox<Integer>;
ObservableList<Integer> intList = FXCollections.observableArrayList();

我用 intList 中的整数填充 ComboBox,方法是:

intBox.getItems().addAll(intList);

我还通过 setEditable(true).

ComboBox 设置为可编辑

问题是,如果我尝试将 intBox.getValue() 的值存储在 Integerint 变量中,我会在运行时得到 "java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer"”。但是如果我尝试将它存储到 String 中,Eclipse 给我编译错误:“类型不匹配:无法从 Integer 转换 到字符串”。所以编译器告诉我它是一个整数,但我仍然不能将它存储在一个整数中,为什么?

我也尝试过各种解决方法,例如 Integer.parseIntgetValue().intValue()Integer.toString(),并将这些值存储在不同数据类型的各种变量中,但它们都给了我相同或相似的错误。

来自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.

基本上,如果 ComboBox 是可编辑的,它将从提供 String 的编辑器 (TextField) 中获取其值。如果您有一个类型不是 String 的可编辑组合框,您需要提供一种方法将字符串从文本字段转换为适当类型的值,反之亦然。所以你需要

intBox.setConverter(new IntegerStringConverter());