且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaFX StackedBarChart自动在不同系列上重复使用相同的颜色:如何避免呢?

更新时间:2023-11-21 21:14:04

颜色在8系列之后被回收(原因是必须对定义的颜色数量进行一定的硬编码限制:JavaFX CSS语法根本无法提供用于计算任意值的足够语法,并且对于超出该限制的系列,需要定义一些颜色.

The colors are recycled after 8 series (the reason is that there has to be some hard-coded limit to the number of colors that are defined: the JavaFX CSS syntax simply does not provide enough syntax for computing arbitrary values, and for series beyond that limit some color needs to be defined).

要为8号以后的系列创建颜色,您需要做两件事:在表示其他系列的节点上设置样式类,并为CSS中的样式设置样式.

To create colors for series beyond the 8th, you need to do two things: set a style class on the nodes representing the additional series, and set the style for those in CSS.

SSCCE:

import java.util.Random;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.StackedBarChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class StackedBarChartExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        StackedBarChart<String, Number> chart = new StackedBarChart<>(new CategoryAxis(), new NumberAxis());

        Random rng = new Random();

        int numSeries = 10 ;
        int defaultColorsDefined = 8 ;


        for (int i = 0; i < numSeries; i++) {
            Series<String, Number> series = new Series<>();
            Data<String, Number> untreated = new Data<>("Untreated", rng.nextDouble());
            series.getData().add(untreated);
            Data<String, Number> treated = new Data<>("Treated", rng.nextDouble());
            series.getData().add(treated);
            series.setName("Series "+i);

            chart.getData().add(series);

            // add style classes for additional series beyond the default support:
            // Note this must be done after adding the series to the chart...
            if (i >= defaultColorsDefined) {
                untreated.getNode().getStyleClass().add("default-color"+i);
                treated.getNode().getStyleClass().add("default-color"+i);
            }
        }

        BorderPane root = new BorderPane(chart);
        Scene scene = new Scene(root);
        scene.getStylesheets().add("stacked-bar-chart.css");
        primaryStage.setScene(scene);
        primaryStage.show();


    }

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

然后按照通常的方式在CSS中定义一些颜色:

And then just define some colors in css in the usual way:

.default-color8.chart-bar {
    -fx-bar-fill: black ;
}
.default-color9.chart-bar {
    -fx-bar-fill: green ;
}