简体   繁体   中英

Run JavaFX app from the command line without GUI

I have a JavaFX in which the user can select files to be processed. Now I want to automate it so that you can run the application from the command line and pass those files as a parameter. I tried to do this:

java -jar CTester.jar -cl file.txt

public static void main(String[] args)
{
    if (Arrays.asList(args).contains("-cl"))
    {
        foo();
    }
    else
    {
        launch(args);
    }
}

The main is executed and the argument is correct, but this still creates the GUI.

From the 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
  • Calls the init() method
  • Calls the start(javafx.stage.Stage) method
  • 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
  • Calls the stop() method

So if I cannot use the main method, how can I create this "alterantive" flow? I thought about creating a normal java application as a wrapper but that seems a little bit overkill for such a simple task. Is there a more elegant way of doing this?

Simply exit the application after calling your foo() method:

Platform.exit();

Here is a quick sample application to demonstrate:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class CLSample extends Application {

    public static void main(String[] args) {

        if (Arrays.asList(args).contains("-cl")) {
            commandLine();
            Platform.exit();
        } else {
            launch(args);
        }

    }

    public static void commandLine() {
        System.out.println("Running only command line version...");
    }

    @Override
    public void start(Stage primaryStage) {

        // Simple Interface
        VBox root = new VBox(10);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(10));

        root.getChildren().add(new Label("GUI Loaded!"));

        // Show the stage
        primaryStage.setScene(new Scene(root));
        primaryStage.setTitle("CLSample Sample");
        primaryStage.show();

    }
}

If you pass -cl , then only the commandLine() method gets called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM