Using command line arguments in Java with JavaFX

I have the following code:

public class Main extends Application {

  @Override
  public void start(Stage primaryStage) throws Exception{
      Parent root = FXMLLoader.load(getClass().getResource("hive.fxml"));
      primaryStage.setTitle("Hive-viewer");
      primaryStage.setScene(new Scene(root, 1600, 900));
      primaryStage.show();
  }


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

I want to know how you will use the file (specified on the command line) in the controller or in the method of the Main class

+4
source share
2 answers

Try getParameters . This should give you command line arguments

As a small example wished (I took the main code from Raphael's answer)

Assuming the controller class is called "MyController"

public class Main extends Application {

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

    FXMLLoader loader=new FXMLLoader(getClass().getResource("hive.fxml"));
    Parent root = loader.load();
    MyController cont=load.getController();
    /*
      This depends on your controller and you have to decide 
      How your controller need the arguments
    */
    cont.setParameter(getParameters()); 

    primaryStage.setTitle("Hive-viewer");
    primaryStage.setScene(new Scene(root, 1600, 900));
    primaryStage.show();
 }


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

You get the arguments from the main method, so you can use it anywhere. You can do something like this:

public class Main extends Application {
    private static String[] arguments;

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

        // e.g. access arguments here or pass them to controller
        for(String arg:arguments) {
            System.out.println(arg);
        }

        Parent root = FXMLLoader.load(getClass().getResource("hive.fxml"));
        primaryStage.setTitle("Hive-viewer");
        primaryStage.setScene(new Scene(root, 1600, 900));
        primaryStage.show();
    }


    public static void main(String[] args) {
        arguments = args;
        launch(args);
    }
  }
0
source

All Articles