在javafx中改变场景

时间:2017-06-04 22:13:24

标签: java javafx timeline

这段代码的问题是什么? 我非常困惑! 我想在主舞台改变我的场景。

public class SignInController {
    @FXML
    TextField SignInPassword;

    @FXML
    TextField SignInUsername;

    @FXML
    CheckBox RememberMe;

    public void signUpScene(MouseEvent mouseEvent) throws IOException {
        Timeline timeline = new Timeline();
        Scene SignUpScene = new Scene(FXMLLoader.load(getClass().getResource("sign up.fxml")),700,700);
        Main.pstage.setScene(SignUpScene);
        timeline.getKeyFrames().addAll(
                new KeyFrame(Duration.ZERO,new KeyValue(SignUpScene.getWidth(),0.0 )),
                new KeyFrame(Duration.millis(1000.0d),new KeyValue(SignUpScene.getWidth(),700.0 ) )
        );

        timeline.play();
    }
}

1 个答案:

答案 0 :(得分:3)

如果要为包含新场景的舞台的宽度设置动画,可以使用Transition

public void signUpScene(MouseEvent mouseEvent) throws IOException {
        Scene SignUpScene = new Scene(FXMLLoader.load(getClass().getResource("sign up.fxml")),700,700);
        Main.pstage.setScene(SignUpScene);

        Rectangle clip = new Rectangle(0, 700);

        Transition animateStage = new Transition() {
            {
                setCycleDuration(Duration.millis(1000));
            }
            @Override
            protected void interpolate(double t) {
                Main.pstage.setWidth(t * 700.0);
            }
        };
        animateStage.play();
    }
}

也许更好的方法是使用剪辑逐渐显示新场景:

public void signUpScene(MouseEvent mouseEvent) throws IOException {

        Parent root = FXMLLoader.load(getClass().getResource("sign up.fxml"));

        Scene SignUpScene = new Scene(root,700,700);
        Main.pstage.setScene(SignUpScene);

        Rectangle clip = new Rectangle(0, 700);
        Timeline animate = new Timeline(
           new KeyFrame(Duration.millis(1000), 
               new KeyValue(clip.widthProperty(), 700.0));
        root.setClip(clip);
        // when animation finishes, remove clip:
        animate.setOnFinished(e -> root.setClip(null));
        animate.play();
    }
}