0

Here is my code to generate 10 bars of different colors. I want to add legend respectively but it only shows yellow legend i can change its color but i want 3 legend.

I think it shows only 1 color because there is only 1 series. Is it possible to add more than 1 legend for a single series?

output:enter image description here

or if i can add this image as legend to the middle left of my chart

enter image description here

i need how to display image in bar chart or how to create 3 different labels for a single series bar chart

import javafx.application.Application;
import javafx.beans.value.*;
import javafx.scene.*;
import javafx.scene.chart.*;
import javafx.stage.Stage;

public class DynamicallyColoredBarChart extends Application {

    @Override
    public void start(Stage stage) {
        final CategoryAxis xAxis = new CategoryAxis();
        xAxis.setLabel("Bars");
        final NumberAxis yAxis = new NumberAxis();
        yAxis.setLabel("Value");

        final BarChart<String, Number> bc = new BarChart<>(xAxis, yAxis);
        bc.setLegendVisible(false);

        XYChart.Series series1 = new XYChart.Series();

        for (int i = 0; i < 10; i++) {
            // change color of bar if value of i is >5 than red if i>8 than blue
            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: red;");
                        }
                    }
                }
            });
            series1.getData().add(data);
        }
        bc.getData().add(series1);
        stage.setScene(new Scene(bc));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
1
  • and is possible to attach an image on left of bar chart which shows legends??
    – H4SN
    Commented Mar 12, 2013 at 10:33

1 Answer 1

1

To put an image to the left you can just add image and chart to HBox:

 HBox root = new HBox(5);
 root.getChildren().addAll(image, bc);
 stage.setScene(new Scene(root));

Not the answer you're looking for? Browse other questions tagged or ask your own question.