JavaFX - moving a window with an effect

I have a non-decorated non-full-screen window that I like to move off the screen when the mouse leaves it, but do it smoothly. I found some JavaFX functions for this - Timeline, but KeyValue for this timeline does not support stage.xProperty - because this property is readonlyProperty. Is there a way to smoothly move my window using JavaFX functions?

+4
source share
1 answer

You can configure the proxy properties that you control with KeyValues ​​in the timeline. The proxy listener can change the actual location of the scene.

window

import javafx.animation.*;
import javafx.application.*;
import javafx.beans.property.*;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.TextAlignment;
import javafx.stage.*;
import javafx.util.Duration;

public class StageSwiper extends Application {

    private static final int W = 350;
    private static final Duration DURATION = Duration.seconds(0.5);

    @Override
    public void start(Stage stage) throws Exception {
        Label instructions = new Label(
            "Window will slide off-screen when the mouse exits it.\n" +
                    "Click the window to close the application."
        );
        instructions.setTextAlignment(TextAlignment.CENTER);

        final StackPane root = new StackPane(instructions);
        root.setStyle("-fx-background-color: null;");

        DoubleProperty stageX = new SimpleDoubleProperty();
        stageX.addListener((observable, oldValue, newValue) -> {
            if (newValue != null && newValue.doubleValue() != Double.NaN) {
                stage.setX(newValue.doubleValue());
            }
        });

        final Timeline slideLeft = new Timeline(
                new KeyFrame(
                        DURATION,
                        new KeyValue(
                                stageX,
                                -W,
                                Interpolator.EASE_BOTH
                        )
                ),
                new KeyFrame(
                        DURATION.multiply(2)
                )
        );
        slideLeft.setOnFinished(event -> {
            slideLeft.jumpTo(Duration.ZERO);
            stage.centerOnScreen();
            stageX.setValue(stage.getX());
        });

        root.setOnMouseClicked(event -> Platform.exit());
        root.setOnMouseExited(event -> slideLeft.play());

        stage.setScene(new Scene(root, W, 100, Color.BURLYWOOD));
        stage.initStyle(StageStyle.UNDECORATED);
        stage.show();

        stage.centerOnScreen();
        stageX.set(stage.getX());
    }


    public static void main(String[] args) {
        launch(args);
    }

}
+4
source

Source: https://habr.com/ru/post/1605903/


All Articles