gpt4 book ai didi

JavaFX LineChart - 更改已更改位置的图例的颜色

转载 作者:行者123 更新时间:2023-11-30 05:31:34 26 4
gpt4 key购买 nike

我有这个代码:

@Override
public void start(Stage primaryStage){

NumberAxis xAxis = new NumberAxis();
xAxis.setLabel("XX");

NumberAxis yAxis = new NumberAxis();
yAxis.setLabel("YY");

LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);

XYChart.Series<Number, Number> series1 = new XYChart.Series<>();
series1.setName("Loooooooooooooongest");
series1.getData().addAll(new XYChart.Data<>(1, 1));

XYChart.Series<Number, Number> series2 = new XYChart.Series<>();
series2.setName("Short");
series2.getData().addAll(new XYChart.Data<>(2, 2));

XYChart.Series<Number, Number> series3 = new XYChart.Series<>();
series3.setName("Loooooong");
series3.getData().addAll(new XYChart.Data<>(3, 3));

lineChart.getData().addAll(series1, series2, series3);
lineChart.setLegendVisible(false); //make default legend invisible

//change color of series
final AtomicInteger index = new AtomicInteger(0);
for(int i = 0; i < 3; i++){

int color = (i*60) + 70;
Platform.runLater(() ->

lineChart.lookupAll(".series" + index.getAndIncrement())
.forEach(e1 -> e1.setStyle("-fx-stroke: rgb(0, 0, " + color + ");" +
"-fx-background-color: rgb(0, 0, " + color + "), white;"))

);

}

//create an hbox for legends
HBox legendBox = new HBox();
legendBox.setStyle("-fx-border-style: solid;" +
"-fx-border-color: lightgray;" +
"-fx-border-width: 1;" +
"-fx-padding: 10;" +
"-fx-background-color: white;" +
"-fx-alignment: center;");

//take all legends and put in hbox
var insets = new Insets(0, 10, 0, 10);
for(Node node : lineChart.lookupAll("Label.chart-legend-item")){

legendBox.getChildren().add(node);
HBox.setMargin(node, insets);

}

//place chart and hbox-legends in borderpane
BorderPane borderPane = new BorderPane();
borderPane.setCenter(lineChart);
borderPane.setBottom(legendBox);

primaryStage.setScene(new Scene(borderPane));
primaryStage.sizeToScene();
primaryStage.centerOnScreen();

primaryStage.show();

}

看起来像这样:

图例的颜色没有改变。

如果我用 HBox 删除该部分并让图例进入原始 Node,它们的颜色就会改变。

为什么如果我移动其他节点中的图例,颜色不再改变?如何更改放置在原始节点之外的其他节点中的图例的颜色?

最佳答案

我找到了解决方案。

for 中,我向 HBox 添加图例:

for(Node node : lineChart.lookupAll("Label.chart-legend-item")){

legendBox.getChildren().add(node);
HBox.setMargin(node, insets);

}

我应该补充:

Label label = (Label)node;
label.getGraphic().setStyle("-fx-background-color: " + mycolor + ", white");

结果是:

for(Node node : lineChart.lookupAll("Label.chart-legend-item")){

Label label = (Label)node;
label.getGraphic().setStyle("-fx-background-color: " + mycolor + ", white");

legendBox.getChildren().add(node);
HBox.setMargin(node, insets);

}

关于JavaFX LineChart - 更改已更改位置的图例的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57417065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com