gpt4 book ai didi

java - 如何在折线图区域内显示图例

转载 作者:行者123 更新时间:2023-12-02 04:39:46 26 4
gpt4 key购买 nike

我想在折线图绘图区域内显示图例。默认情况下,图例显示在图形绘图区域之外,基于传递给图表的 Side.RIGHT、Side.LEFT 等参数。setLegendSide(Side) 如下例所示:-

import javafx.application.Application;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;


public class LineChartSample extends Application {

@Override public void start(Stage stage) {
stage.setTitle("Line Chart Sample");
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Month");
final LineChart<String,Number> lineChart =
new LineChart<String,Number>(xAxis,yAxis);

lineChart.setTitle("Graph Example");

lineChart.setLegendSide(Side.RIGHT);

XYChart.Series series1 = new XYChart.Series();
series1.setName("Legend 1");
series1.getData().add(new XYChart.Data("Jan", 23));
series1.getData().add(new XYChart.Data("Feb", 14));
series1.getData().add(new XYChart.Data("Mar", 15));
series1.getData().add(new XYChart.Data("Apr", 24));
series1.getData().add(new XYChart.Data("May", 34));
series1.getData().add(new XYChart.Data("Jun", 36));


XYChart.Series series2 = new XYChart.Series();
series2.setName("Legend 2");
series2.getData().add(new XYChart.Data("Jul", 55));
series2.getData().add(new XYChart.Data("Aug", 54));
series2.getData().add(new XYChart.Data("Sep", 48));
series2.getData().add(new XYChart.Data("Oct", 27));
series2.getData().add(new XYChart.Data("Nov", 37));
series2.getData().add(new XYChart.Data("Dec", 29));
Scene scene = new Scene(lineChart,800,600);
lineChart.getData().addAll(series1, series2);

stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {
launch(args);
}
}

我找不到在图表区域内显示图例的方法。最多我会有 2-3 个图例并使用 java 8。

谢谢

最佳答案

我认为没有任何干净的方法可以做到这一点。我拿出了您的 setLegendSide 并将其添加到 stage.show()

之后
    for (Node n : lineChart.lookupAll(".chart-legend")) {
n.setTranslateY(-200);
}

场景显示后,您可以“查找”场景中的节点。我找到图例(通过它的 css 名称)并将其向上移动 200。

您还可以翻译 css 文件中的图例

.chart-legend{
-fx-translate-y: -200;
}

只需将 css 文件添加到您的场景中(如果它位于同一个包中,则像这样)。

scene.getStylesheets().add(this.getClass().getResource("css.css").toExternalForm());

这仍然在图表下方留下了空间,因此它并不完美。我注意到您可以将其添加到 css 中,以给 chart-content 更多空间

.chart .chart-content{
-fx-padding: 5 5 -25 5;
}

关于java - 如何在折线图区域内显示图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30301458/

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