[英]Run JavaFX app from the command line without GUI
I have a JavaFX in which the user can select files to be processed. 我有一个JavaFX,用户可以在其中选择要处理的文件。 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. main已执行且参数正确,但这仍会创建GUI。
The entry point for JavaFX applications is the Application class.
JavaFX应用程序的入口点是Application类。 The JavaFX runtime does the following, in order, whenever an application is launched:
每当启动应用程序时,JavaFX运行时都会依次执行以下操作:
- Constructs an instance of the specified Application class
构造指定的Application类的实例
- Calls the init() method
调用init()方法
- Calls the start(javafx.stage.Stage) method
调用start(javafx.stage.Stage)方法
- Waits for the application to finish, which happens when either of the following occur:
等待应用程序完成,这在发生以下任一情况时发生:
- the application calls Platform.exit()
该应用程序调用Platform.exit()
- the last window has been closed and the implicitExit attribute on Platform is true
最后一个窗口已关闭,并且Platform上的hiddenExit属性为true
- Calls the stop() method
调用stop()方法
So if I cannot use the main
method, how can I create this "alterantive" flow? 因此,如果我不能使用
main
方法,该如何创建“替代”流程? I thought about creating a normal java application as a wrapper but that seems a little bit overkill for such a simple task. 我曾考虑过创建一个普通的Java应用程序作为包装器,但是对于这样一个简单的任务而言,这似乎有些过头了。 Is there a more elegant way of doing this?
有没有更优雅的方式做到这一点?
Simply exit the application after calling your foo()
method: 只需在调用
foo()
方法后退出应用程序:
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. 如果传递
-cl
,则仅会调用commandLine()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.