JavaFX - 移动窗口有效

时间:2015-09-04 08:26:59

标签: javafx-8

我有未修饰的非全屏窗口,当鼠标离开它的区域时,我喜欢移动到屏幕边界之外,但是这样做很顺利。我发现了一些JavaFX功能 - 时间轴,但该时间轴的KeyValue不支持stage.xProperty - 因为此属性是readonlyProperty。有没有办法使用JavaFX函数顺利移动窗口?

1 个答案:

答案 0 :(得分:4)

您可以设置通过时间轴中的KeyValues操作的代理属性。代理上的监听器可以修改实际的舞台位置。

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);
    }

}