【问题标题】:Is there a way to give a specific data always the same color in a javaFX chart?有没有办法让特定数据在 javaFX 图表中始终具有相同的颜色?
【发布时间】:2020-07-20 07:11:29
【问题描述】:

我正在制作一个饼图,您可以在其中看到学生参加讲座的情况。 就我个人而言,我认为现在学生的数量在饼图中始终是绿色的会很酷。而缺席的原因全是不同的红色。有没有办法做到这一点?

这是我的 CSS:

.chart {
    -fx-background-color: #484848;
}

.chart-legend {
    -fx-background-color: transparent;
    -fx-text-fill: #fff;
    -fx-border-color: #333;
}

.chart-legend-item {
    -fx-text-fill: #fff;
}

.default-color0.chart-pie { -fx-pie-color: green; }
.default-color1.chart-pie { -fx-pie-color: #ff0000; }
.default-color2.chart-pie { -fx-pie-color: #ce0000; }
.default-color3.chart-pie { -fx-pie-color: #a80000; }
.default-color4.chart-pie { -fx-pie-color: #870000; }
.default-color5.chart-pie { -fx-pie-color: #560000; }
.default-color6.chart-pie { -fx-pie-color: #380000; }
.default-color7.chart-pie { -fx-pie-color: #1c0000; }

.chart-pie-label-line {
    -fx-stroke: #fff;
    -fx-fill: #fff;
}

.chart-pie-label {
    -fx-fill: #fff;
}

这是我的 Java:

private void setUpPieChart() {
    this.pieChart.setLabelLineLength(8f);
    this.updatePieChart();
}

private void updatePieChart() {
    Lecture lecture = this.lectureTable.getSelectionModel().getSelectedItem();

    if (lecture == null)
        this.pieChart.getData().clear();
    else
        // Get all attendances of the lecture object which was obtained from the currently selected row,
        // create a temporary dictionary by grouping all attendances by attendance type and their respective count,
        // sort the dictionary by attendance name and generate a list of pie chart slices for each dictionary item
        this.pieChart.setData(lecture.getAttendances().stream().collect(Collectors.groupingBy(Attendance::getType,
                Collectors.counting())).entrySet().stream().sorted(Comparator.comparing(item -> item.getKey()
                .toString())).map(item -> new PieChart.Data(String.format("%s: %.0f%%", item.getKey(),
                item.getValue() * 100f / lecture.getAttendaceSize()), item.getValue()))
                .collect(toCollection(FXCollections::observableArrayList)));
}

提前致谢:)

【问题讨论】:

  • 我希望您的代码能够正常工作,只要您确保“当前学生”数据始终是第一位的。

标签: java css javafx charts pie-chart


【解决方案1】:

系列的着色是根据添加系列的顺序完成的。现在,您的第一个系列设置为“绿色”,因此只要您调整算法,使添加到 PieChart 的第一个系列为“在校学生人数”,该系列将始终为绿色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-07
    • 2016-11-24
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多