【问题标题】:JavaFX missing Legend classJavaFX 缺少 Legend 类
【发布时间】:2019-08-08 12:41:14
【问题描述】:

我有这个代码:

List<Node> legends = new ArrayList<>(lineChart.lookupAll("Label.chart-legend-item"));
Legend legend1 = (Legend)legends.get(0);

问题是我的 IDE 找不到任何 Legend 类来导入它。

我说的是这个类:https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#legend

我使用的是 Java 10。为什么我的 IDE 找不到 Legend 类?

我想要达到的就是取传说之名。

【问题讨论】:

  • 您在控制台或终端中遇到的错误是什么?
  • @LazarNikolic java: cannot find symbol 因为首先我需要导入 Legend 类,但我的 IDE 看不到类。
  • @trilogy 我知道Platform.runLater 做什么,在我的问题中只是一个简单的例子。运行时和我无法编译代码有什么关系,因为我无法导入Legend

标签: java javafx


【解决方案1】:

看起来 Legend 来自内部 api:

import com.sun.javafx.charts.Legend;

可能在 Java9+ 中被删除

【讨论】:

  • 是的,它似乎在 JavaFX 2 中被删除了
【解决方案2】:

您已导出模块 com.sun.javafx.charts 以访问 Legend 类,因为 Legend 类是内部 API 的一部分。 在 IntelliJ 中,您必须向编译器添加覆盖:

(设置 --> 构建、执行、部署 --> 编译器 --> Java 编译器 --> 覆盖编译器参数)

--add-exports=javafx.controls/com.sun.javafx.charts=ALL-UNNAMED

并在运行配置中添加虚拟机选项。

导入是:

import com.sun.javafx.charts.Legend;

编辑:正如接受的答案所说,它没有被删除。

示例代码:

import com.sun.javafx.charts.Legend;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        Legend legend = new Legend();
        Legend.LegendItem legendItem = new Legend.LegendItem("Test legend item");
        ObservableList<Legend.LegendItem> items = FXCollections.observableArrayList(legendItem);
        legend.setItems(items);
        AnchorPane anchorPane = new AnchorPane(legend);
        Scene scene = new Scene(anchorPane, 400, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

并在编译器选项中添加:

如果您使用 gradle,您还必须将编译器选项添加到 build.gradle。

compileJava {
    options.compilerArgs += ["--add-exports=javafx.controls/com.sun.javafx.charts=ALL-UNNAMED"]
}

【讨论】:

  • 现在我可以导入它了,但是在编译时出现错误:package com.sun.javafx.charts is not visible
  • 我可以用 Java 10 编译它。
【解决方案3】:

TilePane 是 Legend 的超类。 所以你可以投射到 TilePane。

List<Node> legends = new ArrayList<>(lineChart.lookupAll("Label.chart-legend-item"));
TilePane legend1 = (TilePane) legends.get(0);    
legend1.setHgap(10);
legend1.getChildren().remove(..);
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-11
    • 2020-03-13
    • 2020-02-09
    • 2020-03-09
    • 2019-07-06
    • 2020-01-06
    • 2017-09-21
    • 2016-04-06
    相关资源
    最近更新 更多