获取javafx图表中某个值的显示位置

时间:2014-06-10 19:58:31

标签: java javafx-2 javafx-8

我正在使用JavaFX-Charts。我的问题是,我想在特定高度的图表内绘制一条水平线。所以我认为我将获得y轴的显示位置并将其用作线的起点。但getDisplayPosition() - 方法返回错误的值。这是JavaFX8中的错误吗? 这是一些代码:

@Override
    public void start(Stage stage) {
        stage.setTitle("Line Chart Sample");

        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Number of Month");

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

        XYChart.Series series = new XYChart.Series();
        series.setName("My portfolio");

        series.getData().add(new XYChart.Data(-1, 4));
        series.getData().add(new XYChart.Data(0, 2));
        series.getData().add(new XYChart.Data(1, -2));
        series.getData().add(new XYChart.Data(5, 1));

        Group group = new Group();
        Line line = new Line();
        line.setStrokeWidth(3);
        group.getChildren().addAll(chart, line);

        Scene scene = new Scene(group, 800, 400);
        chart.getData().add(series);

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

        line.setStartX(xAxis.getDisplayPosition(0));
        line.setEndX(xAxis.getDisplayPosition(5));
        line.setStartY( yAxis.getDisplayPosition(1.5));
        line.setEndY(yAxis.getDisplayPosition(1.5));

    }

这是运行后的结果:

http://i.stack.imgur.com/UTJMw.jpg

所以我的下一个想法是,我必须使用情节区域的原点,但即使使用此代码,我也没有得到预期的位置:

@Override
public void start(Stage stage) {
        stage.setTitle("Line Chart Sample");

        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Number of Month");

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

        XYChart.Series series = new XYChart.Series();
        series.setName("My portfolio");

        series.getData().add(new XYChart.Data(-1, 4));
        series.getData().add(new XYChart.Data(0, 2));
        series.getData().add(new XYChart.Data(1, -2));
        series.getData().add(new XYChart.Data(5, 1));

        Group group = new Group();
        Line line = new Line();
        line.setStrokeWidth(3);
        group.getChildren().addAll(chart, line);

        Scene scene = new Scene(group, 800, 400);
        chart.getData().add(series);

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

        Node chartPlotArea = chart.lookup(".chart-plot-background");
        double chartZeroX = chartPlotArea.getLayoutX();
        double chartZeroY = chartPlotArea.getLayoutY();

        line.setStartX(xAxis.getDisplayPosition(0)+chartZeroX);
        line.setEndX(xAxis.getDisplayPosition(5)+chartZeroX);
        line.setStartY( yAxis.getDisplayPosition(1.5)+chartZeroY);
        line.setEndY(yAxis.getDisplayPosition(1.5)+chartZeroY);

    }

结果如下:

http://i.stack.imgur.com/K6maX.jpg

对不起,由于声誉不佳,我不允许发布图片。在右上角,这条线总是有点太多了。第二个版本更好,但距离我想要的区域还有一些像素。有人可以帮忙吗?

0 个答案:

没有答案