Crislips
Crislips

Reputation: 460

How to change the colors of specific bars using Javafx BarChart?

This is something that I have been searching for for a while while working on a project. The best I had been able to find was how to change all of the bars or independently based on their specific value. Neither felt like a proper solutions. You might want to change individual bars and the amounts of each may change.

Upvotes: 0

Views: 4354

Answers (1)

Crislips
Crislips

Reputation: 460

The solution I found ended up being fairly simple, but I did not find very good documentation on it and wanted to post it for future use.

NOTE: All of these bars are in the same series. A similar fix could probably be applied to bar charts using multiple series, but that caused a spacing issue for me when each category only needed one bar.

The following code will create a bar chart that with 4 categories to track and adds them to the chart.

public class BarChartExample extends Application {

final static String project = "Project - 20%";
final static String quiz = "Quiz - 10%";
final static String midterm = "Midterm - 30%";
final static String finalexam = "Final - 40%";

@Override
public void start(Stage primaryStage) throws Exception{
    primaryStage.setTitle("Change Bar Color Example");
    final CategoryAxis xAxis = new CategoryAxis();
    final NumberAxis yAxis = new NumberAxis();
    final BarChart<String,Number> barChart = new BarChart<String,Number>(xAxis,yAxis);
    xAxis.setLabel("Assignment Type");
    yAxis.setLabel("Percentage");

    XYChart.Series series = new XYChart.Series();
    series.getData().add(new XYChart.Data(project, 20));
    series.getData().add(new XYChart.Data(quiz, 10));
    series.getData().add(new XYChart.Data(midterm, 30));
    series.getData().add(new XYChart.Data(finalexam, 40));
    barChart.getData().add(series);

This next bit is the part relevant to this post. This is where the color change happens. The bars are considered Nodes, so you can set each bar equal to a node variable and use CSS to change it's style.

    Node n = barChart.lookup(".data0.chart-bar");
    n.setStyle("-fx-bar-fill: red");
    n = barChart.lookup(".data1.chart-bar");
    n.setStyle("-fx-bar-fill: blue");
    n = barChart.lookup(".data2.chart-bar");
    n.setStyle("-fx-bar-fill: green");
    n = barChart.lookup(".data3.chart-bar");
    n.setStyle("-fx-bar-fill: orange");

The rest is just getting rid of the legend (since in this case it's unnecessary) and filling out the remaining necessary code to make it run.

    barChart.setLegendVisible(false);
    VBox vbox = new VBox(barChart);

    Scene scene = new Scene(vbox);

    primaryStage.setScene(scene);
    primaryStage.show();

}

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

}

I hope this helps anyone looking into trying to set bars with specific colors.

Upvotes: 3

Related Questions