user3362305
user3362305

Reputation: 39

JavaFX change stage size from outside the constructor

I have something like

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

What do I have to write into my changeStageSize void to change my stage size?

Upvotes: 0

Views: 2884

Answers (2)

James_D
James_D

Reputation: 209339

Since the MyView instance is the root of the scene, from within MyView you can just do

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

There is no need to delegate this method back to the Application subclass (and you really don't want MyView to have a dependency on that anyway.

Upvotes: 0

fabian
fabian

Reputation: 82461

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

Just set the width and height of the Window. You could use a field instead of passing the stage parameter. If you don't do this IMHO the method should be made static, since no instance members of your application class are accessed.

Upvotes: 1

Related Questions