javafx listview显示的项目太多了

时间:2014-12-15 16:16:07

标签: listview javafx duplicates refresh

我在JavaFX中有一个ListView,当我删除一个项目时,会在ListView中显示更多项目,但不会在列表中显示。

ObservableList和Extractor的声明

Callback<ElectricDeviceType, Observable[]> deviceTypeExtractor = new Callback<ElectricDeviceType, Observable[]>() {
    @Override
    public Observable[] call(ElectricDeviceType t) {
        return new Observable[] { t.maxValue, t.name, t.getDevices() };
    }
};
ObservableList<ElectricDeviceType> deviceTypes = FXCollections
        .observableArrayList(deviceTypeExtractor);    

这里我将设备设置为ListView

    public void setElectricDevices(ElectricDeviceType... list) {
    deviceTypes.addAll(list);
    deviceTypeList.setItems(deviceTypes);
    deviceTypeList
            .setCellFactory(new Callback<ListView<ElectricDeviceType>, javafx.scene.control.ListCell<ElectricDeviceType>>() {
                @Override
                public ListCell<ElectricDeviceType> call(
                        ListView<ElectricDeviceType> listView) {
                    return new ElectricDeviceTypeListViewCell(_this,
                            simulation);
                }
            });
}

Class ElectricDeviceTypeListViewCell

public class ElectricDeviceTypeListViewCell extends ListCell<ElectricDeviceType> {
private MainWindowController controller;
private Simulation simulation;

public ElectricDeviceTypeListViewCell(MainWindowController c, Simulation s) {
    controller = c;
    simulation = s;
}

@Override
public void updateItem(ElectricDeviceType t, boolean empty) {
    super.updateItem(t, empty);
    if (t != null) {
        ElectricDeviceTypeController data = new ElectricDeviceTypeController(controller, simulation);
        data.setInfo(t);
        setGraphic(data.getBox());
    }
}

}

当我从我的可观察列表中删除一个项目时,我的列表视图显示了5个项目而不是2个。但是我的observable只有2个项目。如果我删除了所有项目,那么副本也会被删除。

Before delete

After delete

你能帮帮我吗?

1 个答案:

答案 0 :(得分:3)

我猜你应该更新你的ElectricDeviceTypeListViewCell,以便在更新空白和null值时更改其单元格:

@Override
public void updateItem(ElectricDeviceType t, boolean empty) {
    super.updateItem(t, empty);
    if(empty || t == null) {
      setGraphic(null);
      setText(null);
    }
    else {
        ElectricDeviceTypeController data = new ElectricDeviceTypeController(controller, simulation);
        data.setInfo(t);
        setGraphic(data.getBox());
    }
}