这是我生成 10 个不同颜色的条的代码。我想分别添加图例,但它只显示黄色图例我可以改变它的颜色,但我想要 3 个图例。
我认为它只显示一种颜色,因为只有 1 个系列。是否可以为单个系列添加超过 1 个图例?
输出:
或者如果我可以将此图像作为图例添加到图表的左中
我需要如何在条形图中显示图像或如何为单个系列条形图创建 3 个不同的标签
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);
}
}