Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 would use a file (given with the command line) in the Controller or in a method in the Main class

like image 811
Karatawi Avatar asked Mar 16 '16 10:03

Karatawi


People also ask

How use JavaFX command line?

Step 1: Type "cd" and then write the path starting from "C:" (C drive) to the location where you have saved your code above in . java format. Step 2: Then you need to press Enter so that the command line would open that path. If it yields an error, please recheck the path you passed.

How does Java deal with command line arguments?

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of String s.


1 Answers

Try getParameters. This should give you the command line arguments

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

Assuming the controller class is named "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);
 }
}
like image 56
Clayn Avatar answered Oct 07 '22 04:10

Clayn