Skip to content
Advertisement

How to launch JavaFX source code file from command line?

Since JDK 11, the java command can launch a java source code file, i.e. no need to first compile your java source code. Here is my java source code:

JavaScript

I save this code as file HelloJavaFxWorld.java.
I open a command prompt window and enter the following command.

JavaScript

This is (part of) the output.

JavaScript

How can I run a JavaFX source code file?

Advertisement

Answer

Since JDK 11 is modular, you need to add the JavaFX modules. Try the following.

JavaScript

Replace pathto with the actual path to the JAR files. For example on my Windows 10 machine I have installed JDK 16.0.1 so I am using JavaFX 16 and have placed the [JavaFX] JAR files in this folder:

JavaScript

So my actual command for launching the JavaFX source code file is:

JavaScript

Note that instead of -p, you can use --module-path. Then the command becomes:

JavaScript

Note that I enter that command from the folder containing the java source code file.

The above command may result in the following exception.

JavaScript

This is because, when launching a java source code file, the source code is compiled and the compiled class is stored in memory, i.e. no .class file is created. Method launch(String...), in class javafx.application.Application, calls method forName, in class java.lang.Class in order to load the JavaFX application class. Since there is no HelloJavaFxWorld.class file, method forName throws ClassNotFoundException.

In order to fix that, simply change your java source code to call the other launch method. In other words, change method main to the following.

JavaScript

Now, when I enter the above java command, I get the following window.

screen capture of JavaFX application window

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement