How to pass parameters to JavaFX application?

后端 未结 8 555
温柔的废话
温柔的废话 2020-11-28 13:49

I am running my JavaFX application like this:

public class MainEntry {
    public static void main(String[] args) {
        Controller controller = new Contr         


        
8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 14:27

    Question - I

    I don't even have an instance of my MainStage class !

    Solution

    Your main method doesn't need an instance of MainStage to call the start() of your MainStage. This job is done automatically by the JavaFX launcher.

    From Docs

    The entry point for JavaFX applications is the Application class. The JavaFX runtime does the following, in order, whenever an application is launched:

    Constructs an instance of the specified Application class

    1. Calls the init() method
    2. Calls the start(javafx.stage.Stage) method
    3. Waits for the application to finish, which happens when either of the following occur: the application calls Platform.exit() the last window has been closed and the implicitExit attribute on Platform is true
    4. Calls the stop() method

    and

    The Java launcher loads and initializes the specified Application class on the JavaFX Application Thread. If there is no main method in the Application class, or if the main method calls Application.launch(), then an instance of the Application is then constructed on the JavaFX Application Thread.

    Question - II

    How to pass non-String parameter (controller in my case) to MainStage instance?

    Solution

    Why do you need to pass non-String parameter to MainStage? If you need an controller object, just fetch it from the FXML

    Example

    public class MainEntry extends Application {
    
        @Override
        public void start(Stage stage) throws Exception {
            FXMLLoader loader = new FXMLLoader();
            Pane pane = (Pane) loader.load(getClass().getResourceAsStream("sample.fxml"));
            //Get the controller
            Controller controller = (Controller)loader.getController();
            Scene scene = new Scene(pane, 200, 200);
            stage.setScene(scene);
            stage.show();
        }
    
        public static void main(String[] args) {
            launch(args);// or launch(MainEntry.class)
        }
    }
    

提交回复
热议问题