Msgstr "No item selection" in JavaFX combobox?

What is the correct way to put an element whose value is null inside a ComboBox? I tried using myComboBox.getItems().add(null); , and it works, but whenever the user selects this value in the combo box, an exception is thrown on the console:

 Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.subList(ReadOnlyUnbackedObservableList.java:136) 

So I think this is not the right way to do this. Any clues?

+6
source share
2 answers

In my experience, this is a problem introduced in Java 8u20. In Java 8u05 and 8u11, as well as JavaFX 2.x, you can add null to the list of items, and selecting this item behaved as expected. In Java 8u20, you will get java.lang.IndexOutOfBoundsException when you select null .

Benjamin Gale: You will have to use Java 8u20, select an item in ComboBox, and then select null to see the problem.

Currently, the best option is to create a special null object and the corresponding inscription, as already mentioned.

Alternatively, if you can use the ChoiceBox instead, I think you will find that it works the way you want.

+7
source

I think this should be something with your code that you do not show us, since the SSCCE below works fine and does not throw any exceptions.

 import javafx.application.Application; import javafx.collections.FXCollections; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class NullComboBoxApp extends Application { @Override public void start(Stage primaryStage) { ComboBox<String> cb = new ComboBox<>(FXCollections.observableArrayList( "Option 1", "Option 2", "Option 3" )); cb.getItems().add(null); StackPane root = new StackPane(); root.getChildren().add(cb); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Null ComboBox Example"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 

While this really works, why do you want your users to be able to choose null , outside of me ... is this really the behavior you want? I suspect you really want to clear the current selection, for example:

 cb.getSelectionModel().clearSelection(); 
0
source

Source: https://habr.com/ru/post/975374/


All Articles