JavaFX更改PieChart颜色 [英] Javafx change PieChart color

查看:89
本文介绍了JavaFX更改PieChart颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代表颜色序列的颜色列表.我想将新的颜色序列应用于饼图数据.

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.

推荐答案

您可以使用以下方法在代码中实现自定义馅饼颜色:

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++;
  }
}

请注意,必须在活动场景中显示图表之后应用该方法(否则,data.getNode()调用将返回null).

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).

以下是一些使用它的示例代码.

您可以使用 css样式表实现相同的效果.

You can accomplish the same effect using css stylesheets.

例如,当将样式表应用于给定图表时,包含以下样式定义的css样式表将更改饼图的默认颜色.

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.

样式表方法的优点是样式与代码分开.缺点是必须在创建样式表时而不是在运行时设置颜色,并且将颜色顺序限制为固定数量的颜色(8).

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.

这篇关于JavaFX更改PieChart颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆