缩放在轴上显示日期的折线图

时间:2018-03-28 06:24:45

标签: javafx zoom linechart

我在javafx中寻找一些用于缩放折线图的类/工具。 问题是我在xAxis上使用日期格式。

我找到了一些解决方案,如下:

https://gist.github.com/james-d/7252698 https://github.com/kerner1000/javafx-chart-zooming https://www.programcreek.com/java-api-examples/index.php?source_dir=fancy-chart-master/src/de/tesis/dynaware/javafx/fancychart/zoom/Zoom.java

这些解决方案使用NumberAxis,我尝试在其中集成日期格式,但我没有得到预期的结果。

这是我的代码:

private void setUpZooming(final Rectangle rect, final Node zoomingNode, int min, int max, int step) {
    final ObjectProperty<Point2D> mouseAnchor = new SimpleObjectProperty<>();

    zoomingNode.setOnMousePressed(event -> {
        mouseAnchor.set(new Point2D(event.getX(), event.getY()));
        rect.setWidth(0);
        rect.setHeight(0);
    });

    zoomingNode.setOnMouseDragged(event -> {
        double x = event.getX();
        double y = event.getY();
        rect.setX(Math.min(x, mouseAnchor.get().getX()));
        rect.setY(Math.min(y, mouseAnchor.get().getY()));
        rect.setWidth(Math.abs(x - mouseAnchor.get().getX()));
        rect.setHeight(Math.abs(y - mouseAnchor.get().getY()));
    });

    zoomingNode.setOnMouseReleased(event -> {
        if(rect.getHeight() >= 10 && rect.getWidth() >= 10){
            doZoom(rect, (LineChart<Number, Number>) zoomingNode);
        }
    });

    zoomingNode.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
        if (e.isSecondaryButtonDown()) {
            LineChart<Number, Number> lineChart = (LineChart<Number, Number>) zoomingNode;
            final NumberAxis xAxis = (NumberAxis) lineChart.getXAxis();
            final NumberAxis yAxis = (NumberAxis) lineChart.getYAxis();
            yAxis.setLowerBound(min);
            yAxis.setUpperBound(max);

            rect.setWidth(0);
            rect.setHeight(0);
        }
    });
}

private void doZoom(Rectangle zoomRect, LineChart<Number, Number> chart) {

    Point2D zoomTopLeft = new Point2D(zoomRect.getX(), zoomRect.getY());
    Point2D zoomBottomRight = new Point2D(zoomRect.getX() + zoomRect.getWidth(), zoomRect.getY() + zoomRect.getHeight());

    final NumberAxis yAxis = (NumberAxis) chart.getYAxis();
    Point2D yAxisInScene = yAxis.localToScene(0, 0);
    final NumberAxis xAxis = (NumberAxis) chart.getXAxis();
    Point2D xAxisInScene = xAxis.localToScene(0, 0);

    yAxis.setAutoRanging(false);
    xAxis.setAutoRanging(false);

    double xOffset = zoomTopLeft.getX() - yAxisInScene.getX();
    double yOffset = zoomBottomRight.getY() - xAxisInScene.getY();
    double yAxisScale = yAxis.getScale();
    double xAxisScale = xAxis.getScale();

    xAxis.setLowerBound(xAxis.getLowerBound() + xOffset / xAxisScale);
    xAxis.setUpperBound(xAxis.getLowerBound() + zoomRect.getWidth() / xAxisScale);
    yAxis.setLowerBound(yAxis.getLowerBound() + yOffset / yAxisScale);
    yAxis.setUpperBound(yAxis.getUpperBound() + zoomRect.getHeight() / yAxisScale);

    zoomRect.setWidth(0);
    zoomRect.setHeight(0);
}

0 个答案:

没有答案