Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javafx change PieChart color

Tags:

javafx-2

I have a list of color representing a color sequence. I want to apply the new color sequence to the piechart data.

private final int CASPIAN_COLOR_COUNTS = 8;   
public void setPieChartColor(PieChart chart, List<String> colors) {

    chart.getData().get(i);   // for debug to get the node name (.data)

    /**
     * Set Pie color
     */
    int i = 0;
    for (String color : colors) {
        final Node node = chart.lookup(".data" + i);
        node.getStyleClass().remove("default-color" + (i % CASPIAN_COLOR_COUNTS));
        node.getStyleClass().add(color);
        i++;
    }

but all chart data take Only one color from Caspian color.

like image 828
Khaled Lela Avatar asked Dec 20 '22 08:12

Khaled Lela


1 Answers

You can achieve custom pie colors in code using a method such as:

private void applyCustomColorSequence(
    ObservableList<PieChart.Data> pieChartData, 
    String... pieColors) {
  int i = 0;
  for (PieChart.Data data : pieChartData) {
    data.getNode().setStyle(
      "-fx-pie-color: " + pieColors[i % pieColors.length] + ";"
    );
    i++;
  }
}

Note that the method must be applied after the chart has been shown on an active scene (otherwise the data.getNode() call will return null).

Here is some sample code which uses it.

coloredpiechart


You can accomplish the same effect using css stylesheets.

For example a css stylesheet containing the following style definitions will change the default colors of a pie chart when the stylesheet is applied against a given chart.

.default-color0.chart-pie { -fx-pie-color: #ffd700; }
.default-color1.chart-pie { -fx-pie-color: #ffa500; }
.default-color2.chart-pie { -fx-pie-color: #860061; }
.default-color3.chart-pie { -fx-pie-color: #adff2f; }
.default-color4.chart-pie { -fx-pie-color: #ff5700; }

For an example of the stylesheet based approach: see the "Setting Colors of a Pie Chart" section of the Styling Charts with CSS tutorial.

The stylesheet approach has an advantage that the styles are separated from the code. It has the disadvantage that the colors are must be set the time the stylesheet are created rather than at runtime and the color sequence is restricted to a fixed number of colors (8).

In general, the stylesheet approach is recommended for most applications.

like image 146
jewelsea Avatar answered Dec 28 '22 07:12

jewelsea