5

Here is my code which generates bar chart of 10 values from 0 to 10 . i want to change the color of bars as follows

if i>5 color==red if i>8 color==blue

so the final out will be 0-5(default yellow bars) 6-8(Red bars) 9(blue bar)

kindly help me.. thanks

public class BarChartSample extends Application {

    @Override
    public void start(Stage stage) {
        stage.setTitle("Bar Chart Sample");
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        final BarChart < String, Number > bc = new BarChart < String, Number > (xAxis, yAxis);

        bc.setTitle("Country Summary");
        xAxis.setLabel("bars");
        yAxis.setLabel("Value");
        XYChart.Series series1 = new XYChart.Series();
        series1.setName("...");

        for (int i = 0; i < 10; i++) {
            //here i want to change color of bar if value of i is >5 than red if i>8 than blue
            series1.getData().add(new XYChart.Data("Value", i));
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
H4SN
  • 1,482
  • 3
  • 24
  • 43

1 Answers1

9

I created a sample solution.

The solution works by setting the bar's -fx-bar-fill color to a different color based on the value of the bar's data.

final XYChart.Data<String, Number> data = new XYChart.Data("Value " + i , i);
data.nodeProperty().addListener(new ChangeListener<Node>() {
  @Override public void changed(ObservableValue<? extends Node> ov, Node oldNode, Node newNode) {
    if (newNode != null) {
      if (data.getYValue().intValue() > 8 ) {
        newNode.setStyle("-fx-bar-fill: navy;");
      } else if (data.getYValue().intValue() > 5 ) {
        newNode.setStyle("-fx-bar-fill: firebrick;");
      }  
    }
  }
});

coloredbarchart

jewelsea
  • 150,031
  • 14
  • 366
  • 406
  • i have one more question is it possible to display graph value i.e (value of i) on top of each bar respectively – H4SN Mar 06 '13 at 00:59
  • Please ask additional questions as questions rather than comments, thanks – jewelsea Mar 06 '13 at 01:01
  • @ jewelsea http://stackoverflow.com/questions/15358093/how-to-add-bar-chart-legend-and-change-legand-colour-javafx – H4SN Mar 12 '13 at 10:37
  • 1
    @jewelsea you marked this [link](http://stackoverflow.com/questions/21876711) as a duplicate, but it is not.. this is a **barchart** and the "duplicate" is an **areachart**.. – Kalaschni Mar 05 '14 at 15:21