[英]Run JavaFX app from the command line without GUI
我有一个JavaFX,用户可以在其中选择要处理的文件。 现在,我想使其自动化,以便您可以从命令行运行该应用程序并将这些文件作为参数传递。 我试图这样做:
java -jar CTester.jar -cl file.txt
public static void main(String[] args)
{
if (Arrays.asList(args).contains("-cl"))
{
foo();
}
else
{
launch(args);
}
}
main已执行且参数正确,但这仍会创建GUI。
从文档 :
JavaFX应用程序的入口点是Application类。 每当启动应用程序时,JavaFX运行时都会依次执行以下操作:
- 构造指定的Application类的实例
- 调用init()方法
- 调用start(javafx.stage.Stage)方法
- 等待应用程序完成,这在发生以下任一情况时发生:
- 该应用程序调用Platform.exit()
- 最后一个窗口已关闭,并且Platform上的hiddenExit属性为true
- 调用stop()方法
因此,如果我不能使用main
方法,该如何创建“替代”流程? 我曾考虑过创建一个普通的Java应用程序作为包装器,但是对于这样一个简单的任务而言,这似乎有些过头了。 有没有更优雅的方式做到这一点?
只需在调用foo()
方法后退出应用程序:
Platform.exit();
这是一个快速的示例应用程序来演示:
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();
}
}
如果传递-cl
,则仅会调用commandLine()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.