Saurabh Kumar
Saurabh Kumar

Reputation: 16651

Javafx treeview adding extra icons randomly to the view

I am using javafx treeview and i added icons to my tree view. enter image description here

I use the following code to add the icon to a treeitem. Using Jfeniox library for material design icon. When i click on the tree item the icons appears randomly to the end of the treeview list like in image.

rootTreeView.setCellFactory(tv -> new TreeCell<LeafItem>() {
        @Override
        public void updateItem(final LeafItem item, final boolean empty) {
            super.updateItem(item, empty);

            setText(null);
            setTooltip(null);
            setContextMenu(null);

            if (!empty) {
                if (getTreeItem().equals(rootTreeItem)) {
                    if (item == null) {
                        setText("sasa");
                    }
                }
                if (item instanceof Project) {
                    final Project project = (Project) item;
                    setText(project.getName());
                    setGraphic(createIcon(MaterialDesignIcon.FOLDER));
                }
            }
        }
    });
private MaterialDesignIconView createIcon(final MaterialDesignIcon icon) {
    final MaterialDesignIconView materialDesignIconView = new MaterialDesignIconView(
            icon);
    materialDesignIconView.setSize("1.5em");
    materialDesignIconView.setStyleClass("icon-color");
    return materialDesignIconView;
}

Upvotes: 0

Views: 881

Answers (1)

fabian
fabian

Reputation: 82461

In the updateItem method of the cell you do not set the graphic property to null in case the cell is empty or the item is not a instance of Project. Since items can be reassigned to the cell you need to do this in order to remove the icon from the cell:

@Override
public void updateItem(final LeafItem item, final boolean empty) {
    super.updateItem(item, empty);

    setText(null);
    setTooltip(null);
    setContextMenu(null);
    setGraphic(null);

    ...

Upvotes: 2

Related Questions