add Marker to JavaFX XYChart - Java JavaFX

Java examples for JavaFX:Chart

Description

add Marker to JavaFX XYChart

Demo Code

/*/* w w w .j av  a2  s .com*/
 * Copyright 2002-2014 SCOOP Software GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import javafx.event.EventHandler;
import javafx.geometry.Bounds;

import javafx.geometry.Point2D;
import javafx.scene.Node;

import javafx.scene.chart.XYChart;

import javafx.scene.input.MouseEvent;

import javafx.scene.layout.StackPane;

import javafx.scene.shape.Line;

public class Main {
    public static void addMarker(final XYChart<?, ?> chart,
            final StackPane chartWrap) {
        final Line valueMarker = new Line();
        final Node chartArea = chart.lookup(".chart-plot-background");

        chartArea.setOnMouseMoved(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Point2D scenePoint = chart.localToScene(event.getSceneX(),
                        event.getSceneY());
                Point2D position = chartWrap.sceneToLocal(
                        scenePoint.getX(), scenePoint.getY());

                Bounds chartAreaBounds = chartArea.localToScene(chartArea
                        .getBoundsInLocal());
                valueMarker.setStartY(0);
                valueMarker
                        .setEndY(chartWrap.sceneToLocal(chartAreaBounds)
                                .getMaxY()
                                - chartWrap.sceneToLocal(chartAreaBounds)
                                        .getMinY());

                valueMarker.setStartX(0);
                valueMarker.setEndX(0);
                valueMarker.setTranslateX(position.getX()
                        - chartWrap.getWidth() / 2);

                double ydelta = chartArea.localToScene(0, 0).getY()
                        - chartWrap.localToScene(0, 0).getY();
                valueMarker.setTranslateY(-ydelta * 2);
            }
        });

        chartWrap.getChildren().add(valueMarker);
    }
}

Related Tutorials