如何在JavaFX中进行自定义LineChart控件?

时间:2018-05-14 13:11:51

标签: java javafx javafx-8

我的JavaFX项目中有一个自定义的LineChartWithMarkers控件。 我在Java(FX)编程中暂停了两年,发现在Java 10中不再存在LineChartBuilder。 我能够找到一些文档说它在版本8中已被弃用,但不是如何替换它。

如何修复我的代码以使用Java 10?

这就是我所拥有的:

public class LineChartWithMarkersBuilder extends LineChartBuilder {
    private Axis<Number> xAxis ;
    private Axis<Number> yAxis ;        
    private ObservableList<Series<Number,Number>> data ;

    public static LineChartWithMarkersBuilder create() {
        return new LineChartWithMarkersBuilder();
    }

    public LineChartWithMarkersBuilder xAxis(Axis<Number> xAxis) {
        this.xAxis = xAxis ;
        return this ;
    }

    public LineChartWithMarkersBuilder yAxis(Axis<Number> yAxis) {
        this.yAxis = yAxis ;
        return this ;
    }


    public LineChartWithMarkers<Number, Number> build() {
        xAxis = new NumberAxis();
        yAxis = new NumberAxis();
        return new LineChartWithMarkers<Number, Number>( xAxis, yAxis);

    }
}

和自定义LineChartWithMarkers:

public class LineChartWithMarkers<X extends Number, Y extends Number> extends LineChart<X, Y>  {

    private ObservableList<Data<Number, Number>> verticalMarkers;


    public LineChartWithMarkers(Axis<X> xAxis, Axis<Y> yAxis) {
        super(xAxis, yAxis);
        this.setCreateSymbols(false);
        verticalMarkers = FXCollections.observableArrayList(data -> new Observable[] {data.XValueProperty()});
        verticalMarkers.addListener((InvalidationListener)observable -> layoutPlotChildren());
    }
    (...)
}

我使用.fxml像这样:

...
                <LineChartWithMarkers fx:id="chartFit" createSymbols="false" layoutX="14.0" layoutY="54.0" prefHeight="499.0" prefWidth="987.0" AnchorPane.bottomAnchor="162.0" AnchorPane.leftAnchor="14.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="54.0">
                <xAxis>
                    <NumberAxis side="BOTTOM" />
                </xAxis>
                <yAxis>
                    <NumberAxis side="LEFT" />
                </yAxis>
            </LineChartWithMarkers>
...

1 个答案:

答案 0 :(得分:1)

所有JavaFX构建器类在Java 8中都已弃用,在Java 9中已删除。只需完全删除构建器类。要允许FXMLLoader顶部实例化没有无参构造函数的类,请在构造函数参数上使用@NamedArg注释:

public class LineChartWithMarkers<X extends Number, Y extends Number> extends LineChart<X, Y>  {

    private ObservableList<Data<Number, Number>> verticalMarkers;


    public LineChartWithMarkers(
            @NamedArg("xAxis") Axis<X> xAxis, 
            @NamedArg("yAxis") Axis<Y> yAxis) {
        super(xAxis, yAxis);
        this.setCreateSymbols(false);
        verticalMarkers = FXCollections.observableArrayList(data -> new Observable[] {data.XValueProperty()});
        verticalMarkers.addListener((InvalidationListener)observable -> layoutPlotChildren());
    }
    (...)
}

可以在What is the purpose of @NamedArg annotation in javaFX 8?

中找到@NamedArg注释的完整讨论