makes a stage draggable using a given JavaFX node - Java JavaFX

Java examples for JavaFX:Node

Description

makes a stage draggable using a given JavaFX node

Demo Code


import javafx.animation.FadeTransition;
import javafx.animation.SequentialTransition;
import javafx.animation.SequentialTransitionBuilder;
import javafx.animation.TranslateTransition;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main{
    private static double x;
    private static double y;
    private static double initialX;
    private static double initialY;
    /**/*from  ww  w  .  j  av  a  2  s .c o m*/
         * makes a stage draggable using a given node
         *
         * @param n
         * @param primaryStage
         */
        public static void addDragListeners(final Node n, Stage primaryStage) {

    n.setOnMousePressed((MouseEvent mouseEvent) -> {
        EffectUtil.x = n.getScene().getWindow().getX() - mouseEvent.getScreenX();
        EffectUtil.y = n.getScene().getWindow().getY() - mouseEvent.getScreenY();
    });

    n.setOnMouseDragged((MouseEvent mouseEvent) -> {
        primaryStage.setX(mouseEvent.getScreenX() + EffectUtil.x);
        primaryStage.setY(EffectUtil.y + mouseEvent.getScreenY());
    });
}
    public static void addDragListeners(final Node n) {
    n.setOnMousePressed((MouseEvent me) -> {
        if (me.getButton() != MouseButton.MIDDLE) {
            initialX = me.getSceneX();
            initialY = me.getSceneY();
        } else {
            n.getScene().getWindow().centerOnScreen();
            initialX = n.getScene().getWindow().getX();
            initialY = n.getScene().getWindow().getY();
        }
    });

    n.setOnMouseDragged((MouseEvent me) -> {
        if (me.getButton() != MouseButton.MIDDLE) {
            n.getScene().getWindow().setX(me.getScreenX() - initialX);
            n.getScene().getWindow().setY(me.getScreenY() - initialY);
        }
    });
}
}

Related Tutorials