【问题标题】:rows color javafx listview行颜色 javafx listview
【发布时间】:2018-12-24 23:46:31
【问题描述】:

ListView 控件有问题。我希望我的奇数行和偶数行有不同的颜色,但我想用代码而不是 FXML 来做。例如:

  • 第一行 - 绿色
  • 第二行 - 红色
  • 第三行 - 颜色绿色
  • 第四行 - 红色

现在我有这样的东西,但这改变了所有 ListView 的背景而不是单行。

rightListView.setCellFactory(param -> new ListCell<Group>() {
        @Override
        protected void updateItem(Group item, boolean empty) {
            super.updateItem(item, empty);

            if (empty || item == null || item.getName() == null) {
                setText(null);
            } else {
                setText(item.getName());
            }
            for(int k=0;k<rightListView.getItems().size();k++) {
                if (k%2==0)
                    setStyle("-fx-background-color: blue;");
                else
                    setStyle("-fx-background-color: red;");
            }
        }
    });

我该如何解决这个问题?

【问题讨论】:

    标签: listview javafx


    【解决方案1】:

    实现此结果的最简单方法是 CSS 样式表:

    scene.getStylesheets().add("style.css");
    

    style.css

    .list-view .list-cell:odd {
        -fx-background-color: red;
    }
    
    .list-view .list-cell:even {
        -fx-background-color: blue;
    }
    

    您可能需要将 .list-view 选择器替换为选择应应用此样式的 ListView 的选择器。这样做的好处是,它允许您保持:selected 样式比使用代码更容易。

    .list-view .list-cell:odd {
        -fx-background-color: red;
    }
    
    .list-view .list-cell:even {
        -fx-background-color: blue;
    }
    
    .list-view .list-cell:selected:odd,
    .list-view .list-cell:selected:even {
        -fx-background-color: -fx-background;
    }
    

    如果你想在你的java代码中使用setStyle来应用样式,你应该在updateItem中使用getIndex

    rightListView.setCellFactory(param -> new ListCell<Group>() {
        @Override
        protected void updateItem(Group item, boolean empty) {
            super.updateItem(item, empty);
    
            if (empty || item == null) {
                setText(null);
                setStyle(null);
            } else {
                setText(item.getName());
                setStyle(getIndex() % 2 == 0 ? "-fx-background-color: blue;" : "-fx-background-color: red;");
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 2017-04-06
      • 2023-03-06
      • 2015-11-01
      相关资源
      最近更新 更多