Look at [the start of] the stack trace...
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 5
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at javafx.base/com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
at jfxprjct/jfxtests.ComboBoxTest$1.handle(ComboBoxTest.java:52)
Now look at line 52 in file ComboBoxTest.java
.
(Note that it may be a different line number in your stack trace.)
For me, this is line 52
if(!items.get(i).equals(cbItems.getValue())){
In other words, the value of i
is -1
(minus one). And i
is assigned a value in the line preceding the if
statement.
int i = cbItems.getSelectionModel().getSelectedIndex();
In other words, there is no selected index. So you should first check the value of i
and not assume that it is a valid index value.
However, a better condition (in my opinion) would be
if(!cbItems.getItems().contains(cbItems.getValue())){
Then you don't need the selected index at all.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…