Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javafx 2.0 How-to Application.getParameters() in a Controller.java file

Tags:

java

javafx-2

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>
like image 208
ohFRY Avatar asked Apr 13 '12 03:04

ohFRY


1 Answers

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:

  • Passing Parameters JavaFX FXML
  • Multiple FXML with Controllers, share object
like image 57
Sergey Grinev Avatar answered Sep 28 '22 13:09

Sergey Grinev