选择颜色 JavaFx ListView

Selecting Color JavaFx ListView

我正在使用自定义 ListCells (CellFactory) 创建自定义 ListView。 这个自定义单元格从一个包含面板的 fxml 文件中获取它的设计。 现在这个面板有一个固定的背景颜色,但是我想在这个单元格被选中时改变这个面板的背景。

在css中我只能改变整个单元格的背景,不能改变内容。

也许你能给我一些小费。

编辑:这是一个最小的示例:当单元格被选中时,面板的背景应该变成蓝色。

 public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        BorderPane root = new BorderPane( );

        ListView listview = new ListView<String>(  );
        ObservableList<String> items = FXCollections.observableArrayList (
            "String1", "String2", "String3", "String4");
        listview.setItems(items);

        listview.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
                                    @Override
                                    public ListCell<String> call(ListView<String> list) {
                                        return new CustomRectCell();
                                    }
                                }
        );

        root.setCenter( listview );
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    static class CustomRectCell extends ListCell<String> {
        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            Pane rect = new Pane();
            if (item != null) {

                // This does not work
                if(isSelected())
                    rect.setStyle( "-fx-background-color: Blue;" );
                else
                    rect.setStyle( "-fx-background-color: Red;" );

                setGraphic(rect);

            }
        }
    }
}

CustomRectCell 无法工作有两个原因:

  1. 选择与项目无关
  2. 您永远不会删除 graphic 因此单元格变空(例如,如果项目数量减少),您的单元格将保持填充状态。

您可以覆盖 updateSelected 以分配背景颜色:

static class CustomRectCell extends ListCell<String> {

    private final Pane rect = new Pane();

    {
        // initialize with default background
        rect.setStyle("-fx-background-color: Blue;");
    }

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

        setGraphic((empty || item == null) ? null : rect);
    }

    @Override
    public void updateSelected​(boolean selected) {
        super.updateSelected(selected);
        rect.setStyle(selected ? "-fx-background-color: Red;" : "-fx-background-color: Blue;");
    }
}

或者,您可以将 CSS 样式表添加到场景并将其用于样式设置:

static class CustomRectCell extends ListCell<String> {

    private final Pane rect = new Pane();

    {
        rect.getStyleClass().add("rect");
    }

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

        setGraphic((empty || item == null) ? null : rect);
    }
}

CSS 样式表

.list-cell .rect {
    -fx-background-color: blue;
}

.list-cell:selected .rect {
    -fx-background-color: red;
}