how to add 3 legend for a single series barchart?? JAVAFX

无人久伴 提交于 2019-12-11 17:57:25

问题


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:

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

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:


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


来源:https://stackoverflow.com/questions/15358093/how-to-add-3-legend-for-a-single-series-barchart-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!