これは、異なる色の 10 本のバーを生成するコードです。凡例をそれぞれ追加したいのですが、黄色の凡例しか表示されません。色を変更できますが、3つの凡例が必要です。
1シリーズしかないので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);
}
}