JavaFX淡出舞台并关闭

4
我很难确定这是否可能。大多数人想要的通用行为是淡出一个node的扩展,这完全可以通过FadeTransition实现。
然而,我正在尝试淡出整个舞台,所以想象一下关闭运行中的程序,而不是简单地关闭窗口(即显示->不显示),我希望窗口(stage)像吐司或通知一样在2秒内淡出。
1个回答

8
使用关键帧创建一个时间轴,改变场景根节点的不透明度。同时确保设置舞台样式和场景填充为透明。然后在时间轴结束时使程序退出。
下面是一个应用程序,其中有一个大按钮,单击该按钮将需要2秒钟淡出,然后程序将关闭。
public class StageFadeExample extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        Stage stage = new Stage();
        stage.initStyle(StageStyle.TRANSPARENT); //Removes window decorations

        Button close = new Button("Fade away");
        close.setOnAction((actionEvent) ->  {
            Timeline timeline = new Timeline();
            KeyFrame key = new KeyFrame(Duration.millis(2000),
                           new KeyValue (stage.getScene().getRoot().opacityProperty(), 0)); 
            timeline.getKeyFrames().add(key);   
            timeline.setOnFinished((ae) -> System.exit(1)); 
            timeline.play();
        });

        Scene scene = new Scene(close, 300, 300);
        scene.setFill(Color.TRANSPARENT); //Makes scene background transparent
        stage.setScene(scene);
        stage.show();
    }

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

我试图使用时间轴,但我的版本很卡顿,并且有一个奇怪的效果,只有在我在上面摆动鼠标时才能播放转换...但是这个方法完美地解决了问题!谢谢! - Jason M.
这里也可以使用FadeTransition,不过Timeline也可以。对于JavaFX应用程序,使用Platform.exit而不是System.exit。Platform.exit允许应用程序的stop方法运行。 - jewelsea
在同一上下文中,关闭主要阶段也将平稳退出应用程序。 - Jason M.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接