Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX - Why does JavaFx create a primary stage instead of allowing me to do it?

Tags:

java

javafx-8

I would like to create a class called EnhancedStage which adds functionality to Stage. The problem is, javaFx creates the primary stage and passes it into the application, instead of allowing me to create it. This way I'm not able to use my own class for the primary stage. I don't understand why the system creates the Stage, and would I be losing anything by not using that stage and instead constructing another one ? Thanks


1 Answers

If you don't want to use the stage which is a parameter of the start() method, then don't call show() on that stage, just create your own stage and only call show() on your custom stage. I suggest doing this inside the start method rather than via a runLater call from init. I don't see any significant drawback in such an approach.

As to why a stage is passed in start, MadProgrammer's guess is as good as any: Simplifies life for programmers, removes some boilerplate code from basic apps and limits app startup coding errors. For all those reasons, for most people, I'd generally just advise using the provided stage rather than creating your own.

Suggested approach if you need or desire to use a stage subclass for your primary stage:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class StageTester extends Application {
    @Override public void start(final Stage systemStage) throws Exception {
        UserStage userStage = new UserStage();
        userStage.show();
    }

    private class UserStage extends Stage {
        FlowPane layout = new FlowPane();

        UserStage() {
            super();
            foo();
            setScene(new Scene(layout));
        }

        public void foo() {
            layout.getChildren().add(new Label("foo"));
        }
    }

    public static void main(String[] args) { launch(args); }
}
like image 82
jewelsea Avatar answered Sep 18 '25 13:09

jewelsea