是的,还有更早的 线程 和 指南 在这个问题上。他们告诉我,要么 setValue(null)
或 getSelectionModel().clearSelection()
应该是答案。但做任何一个都会给我一个 java.lang.IndexOutOfBoundsException
.
我想做的是每次在组合框中写东西的时候清除选择。这是因为当你在组合框中写了一些东西,而在组合框的弹出式中仍然有其他的东西被选中时,会引起一些问题,看起来很奇怪。
这是一个SSCCE。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.converter.IntegerStringConverter;
public class SSCCE extends Application {
@Override
public void start(Stage stage) {
HBox root = new HBox();
ComboBox<Integer> cb = new ComboBox<Integer>();
cb.setEditable(true);
cb.getItems().addAll(1, 2, 6, 7, 9);
cb.setConverter(new IntegerStringConverter());
cb.getEditor().textProperty()
.addListener((obs, oldValue, newValue) -> {
// Using any of these will give me a IndexOutOfBoundsException
// Using any of these will give me a IndexOutOfBoundsException
//cb.setValue(null);
//cb.getSelectionModel().clearSelection();
});
root.getChildren().addAll(cb);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
你遇到了这个问题 JavaFX ComboBox改变值会导致IndexOutOfBoundsException异常。 的问题,这就是导致 IndexOutOfBoundsException
. 这些都有点麻烦。
反正你的尝试有一点逻辑问题:清除选中的值会导致编辑器更新其文本,所以即使这样做有效,也会让用户无法输入。所以你要检查改变的值是不是输入的那个。这似乎可以解决这两个问题。
cb.getEditor().textProperty()
.addListener((obs, oldValue, newValue) -> {
if (cb.getValue() != null && ! cb.getValue().toString().equals(newValue)) {
cb.getSelectionModel().clearSelection();
}
});
你可能需要改变 toString()
调用,具体取决于你使用的转换器。在这种情况下,它将工作。