JavaFX从构造函数外部更改阶段大小

时间:2016-09-20 12:23:14

标签: java javafx resize stage

我有类似

的东西
public class MyClass extends Application {

    public void start(Stage stage) {
        MyModel model = new MyModel();
        MyController controller = new MyController(model);
        MyView view = new MyView(model, controller);
        Scene scene = new Scene(view);

        stage.setTitle("MyTitle");
        stage.setScene(scene);
        stage.sizeToScene();
        stage.show();
        view.requestFocus();
    }

    public void changeStageSize(int width, int height) {
        ...
    }

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

如果要更改我的阶段大小,我必须写入我的changeStageSize void?

2 个答案:

答案 0 :(得分:1)

@Override
public void start(Stage primaryStage) {
    Button btn = new Button("Resize");
    btn.setOnAction((ActionEvent event) -> {
        changeStageSize(primaryStage, 800, 500);
        primaryStage.centerOnScreen();
    });

    StackPane root = new StackPane(btn);
    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}

public void changeStageSize(Window stage, int width, int height) {
    stage.setWidth(width);
    stage.setHeight(height);
}

只需设置width的{​​{1}}和height即可。您可以使用字段而不是传递Window参数。如果你不这样做恕我直言,方法应该是静态的,因为没有访问你的应用程序类的实例成员。

答案 1 :(得分:0)

由于MyView实例是场景的根,所以来自MyView ,你可以做到

Window win = getScene().getWindow();
win.setWidth(...);
win.setHeight(...);

无需将此方法委托给Application子类(并且您真的不希望MyView依赖于此。