JavaFX BarChart bar color


Question

How can you change the color of a bar in a JavaFX BarChart?

I couldn't find a way to change the color through the css setStyle Method.

1
3
1/9/2019 8:54:49 AM

Accepted Answer

you can set color of bar using css

.default-color0.chart-bar { -fx-bar-fill: ***** }
.default-color1.chart-bar { -fx-bar-fill: ***** }
...

Using setStyle Method :

use lookupAll method in Node class,

Finds all Nodes, including this one and any children, which match the given CSS selector. If no matches are found, an empty unmodifiable set is returned. The set is explicitly unordered.

code :

  //set first bar color
  for(Node n:barChart.lookupAll(".default-color0.chart-bar")) {
            n.setStyle("-fx-bar-fill: red;");
        }
   //second bar color
   for(Node n:barChart.lookupAll(".default-color1.chart-bar")) {
            n.setStyle("-fx-bar-fill: green;");
        }
4
1/10/2013 4:50:01 PM

From JavaFX8 you can simply use the .chart-bar selector:

.chart-bar {
    -fx-bar-fill: red; 
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon