JavaFX ListView 更改单个 Cells/Items/Rows 的颜色

JafaFX ListView change Color of single Cells/Items/Rows

可能这个问题的答案很简单,所以我会尽量保持我的post。

我的问题 我希望通过 JavaFX ColorPicker 自定义不同 Cells/Rows/ItemsText-Color。我的代码确实有效,但并不像我想要的那样。每次将新的 Item 添加到 ListView 时,整个 ListView 都会更改其 Text-ColorText-Color 被选为最新 Item.

这是我的代码(完整的 class 链接如下,但我认为不需要)

@FXML
void handleAdd(){   //When add button is clicked

    fontSize = 16.0;

    listView.setCellFactory(cell -> {
        ListCell<String> cel = new ListCell<String>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (item != null) {
                    setTextFill(colorPicker.getValue());
                    setFont(Font.font(16));
                    setText(item);
                } else {
                    setText("");
                }
            }
        };
        return cel;
    });


    listView.getItems().add(input.getText()); //input is my TextField

    input.clear();
}

full class

提前致谢!

使用 ListView 的项目类型,除字符串

外还包含 ObjectProperty<Color>
private static class ListItem {
    public ListItem(String text) {
        this.text = text;
    }

    private final String text;
    private final ObjectProperty<Color> color = new SimpleObjectProperty(Color.BLACK);
}
ListView<ListItem> listView;
listView.setCellFactory(cell -> {
    ListCell<ListItem> cel = new ListCell<ListItem>() {
        @Override
        protected void updateItem(ListItem item, boolean empty) {
            super.updateItem(item, empty);
            if (item != null) {
                textFillProperty().bind(item.color);
                setFont(Font.font(16));
                setText(item.text);
            } else {
                setText("");
                textFillProperty().unbind();
                setTextFill(Color.BLACK);
            }
        }
    };
    return cel;
});

这样你只需要将 属性 设置为不同的值,如果你想改变颜色,例如:

ListItem selectedItem = listView.getSelectionModel().getSelectedItem();
if (item != null) {
    item.color.set(Color.RED);
}