为什么listView.getSelectionModel()。getSelectedIndex()返回-1?

时间:2016-06-30 13:54:23

标签: java javafx

过去几天,这在运行时造成了大量错误 - 并发修改异常和空指针异常

我不记得我添加了什么,但是在这个段中添加了一段代码并且它抛出一个数组超出范围的异常导致我发现它在Null指针异常之上抛出一个负数索引它当viewList中没有任何内容时抛出。

为什么这样做?本周我刚开始和javafx一起玩弄这让我相信我一定搞砸了?

ObservableList<BusinessCard> observableList = FXCollections.observableArrayList(); //initialized above

    // ListView Listener, changes text fields for the selected B.C in ViewList
    try {
        listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<BusinessCard>() {
            @Override
            public void changed(ObservableValue<? extends BusinessCard> arg0, BusinessCard oldval,BusinessCard newVal) {
                int index = listView.getSelectionModel().getSelectedIndex();

                if(index == -1) return;  //Fix          

                BusinessCard card = observableList.get(index);                      
                setDataFields(card);         
            }
        });
    } catch (NullPointerException e1) {
        // Do nothing, NullPointer thrown when list is empty
    }

1 个答案:

答案 0 :(得分:3)

我认为documentation for the selectedIndex property在这里很清楚。

  

指的是所选的index属性,用于指示   当前在选择模型中选择的索引值。选中   index是-1,表示没有选择,或者是   在基础数据模型范围内的整数值   大小