10
votes

Considering the following sample.

How to access to arguments/parameters of the application in the controller?

Thank you.


NB: I've tried to mix App.java and MyController.java in only one Class file, but didn't help.


App.java (simplified):

public class App extends Application {

    public static void main(String[] args) {
        Application.launch(App.class, args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        // output arguments in console
        System.out.println(getParameters().getNamed().toString());

        Parent root = FXMLLoader.load(getClass().getResource("MyView.fxml"));
        final Scene scene = new javafx.scene.Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}

MyController.java (simplified):

public class MyController implements Initializable {

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // HOW TO getParameters() HERE ?
    }

    @FXML
    private Button myButton;

    @FXML
    private void my_Action(ActionEvent event) {
        // HOW TO getParameters() HERE ?
    }

}

MyView.fxml (simplified):

<AnchorPane fx:id="root" fx:controller="mainpackage.MyController">
    <children>
        <Button fx:id="myButton" onAction="#my_Action" text="Start" />
    </children>
</AnchorPane>
3

3 Answers

18
votes

1. The most straightforward way is to save them in the app:

public class App extends Application {

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

  public static String parameters;

  @Override
  public void start(Stage primaryStage) throws Exception {

    parameters = getParameters().getNamed().toString();

    Parent root = FXMLLoader.load(getClass().getResource("MyView.fxml"));
    final Scene scene = new javafx.scene.Scene(root);
    primaryStage.setScene(scene);
    primaryStage.show();
  }

}

and read them in the controller:

public class MyController implements Initializable {

  @Override
  public void initialize(URL url, ResourceBundle rb) {
     System.out.println(App.parameters);
  }

2. A bit more complex (and better in general) approaches are described in the next answers:

0
votes
    public static <T extends Node, P> T load(String resource, final P parameter)
            throws MoisException {
        try {
            logger.debug("resource: {}; parameter: {}", resource, parameter);
            FXMLLoader loader = new FXMLLoader(getResource(resource));
            // pass parameter into Controller,before invoke the initialize()
            loader.setControllerFactory(new Callback<Class<?>, Object>() {
                @Override
                public Object call(Class<?> param) {
                    Object controller = null;
                    try {
                        controller = ReflectUtil.newInstance(param);
                    } catch (InstantiationException e) {
                        throw new MoisException("can't new instance for: " + param.getName(), e);
                    } catch (IllegalAccessException e) {
                        throw new MoisException("can't new instance for: " + param.getName(), e);
                    }
                    if (controller instanceof ParameterAware) {
                        ((ParameterAware<P>) controller).setParameter(parameter);
                    }
                    return controller;
                }
            });
            T node = (T) loader.load();
            // pass parameter to node
            node.setUserData(parameter);
            return node;
        } catch (IOException e) {
            throw new MoisException("can't load the file: " + resource, e);
        }
    }

and the ParameterAware:

public interface ParameterAware<T> {
    void setParameter(T param);
}
0
votes

every time you load an fxml file it will make a controller instance if you can get that instace you can pass many data from the class where fxml is called . that will avoid unnecesary static objects .

public class App extends Application {

    public static void main(String[] args) {
        Application.launch(App.class, args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        // output arguments in console
        System.out.println(getParameters().getNamed().toString());
        
        
        String parameters = getParameters().getNamed().toString();
        FXMLLoader fxmlLoader  = new FXMLLoader(this.getClass().getResource("MyView.fxml"));
                  
        Parent root = fxmlLoader.load();
        // cast MyController instance from fxmlLoader object
        MyController myController =(MyController)fxmlLoader.getController();
        // pass parameters string to myController via public method  setParameters()
        myController.setParameters(parameters);
        
        final Scene scene = new javafx.scene.Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}

    

   

now you get parameters String from App class as a private field in MyController

    public class MyController implements Initializable {

    private String parameters;

    // method called in App class
    public void setParameters(String parameters) {
        this.parameters = parameters;

    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // HOW TO getParameters() HERE ?
    }

    @FXML
    private Button myButton;
    @FXML
    private Label label;

    @FXML
    private void my_Action(ActionEvent event) {
        label.setText("parameters from App class in MyController :" + parameters);
    }

}

I added a label in fxml file to see what happens

 <AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/17" fx:controller="com.giovanni.mavenproject1.MyController">
    <children>
        <VBox alignment="CENTER" prefHeight="400.0" prefWidth="600.0" spacing="20.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <children>
                <Button fx:id="myButton" onAction="#my_Action" text="Start" />
                <Label fx:id="label" text="Label" />
            </children>
        </VBox>
    </children>  
</AnchorPane>

and this is the result when button is pressed passing params