murray
murray

Reputation: 787

Why cannot run compiled JavaFX 11 class?

Following instructions at https://openjfx.io/openjfx-docs/#install-javafx, I compiled the sample HelloFX.java via:

 javac --module-path $PATH_TO_FX --add-modules=javafx.controls /Users/me/Documents/java/HelloFX.java 

But now if I attempt to run that...

 java --module-path $PATH_TO_FX --add-modules=javafx.controls /Users/me/Documents/java/HelloFX

... I get error:

 Error: Could not find or load main class .Users.me.Documents.java.HelloFX
 Caused by: java.lang.ClassNotFoundException: /Users/me/Documents/java/HelloFX 

Yet the file reported as not found is there:

 ls -l /Users/me/Documents/java/HelloFX.class
 -rwxr--r--  1 me  staff  1336 Oct 30 16:01 /Users/murray/Documents/java/HelloFX.class

(I had already changed permissions to add u+x in case that was the issue, but apparently that was not the trouble.

What's wrong?

(Yes, $PATH_TO_FX does point to javafx-sdk-11/lib.)

Upvotes: 1

Views: 2990

Answers (1)

José Pereda
José Pereda

Reputation: 45486

This question was already answered in the openjfx-dev mailing list:

The "java" command expects a fully-qualified class name, not a file path as its argument

For completion:

  • The javac command deals with filenames, which means you can compile a java file from any location:

    javac [ options ] [ sourcefiles ]
    
  • However the java command deals with classes:

    java [options] mainclass [args...] 
    

    where mainclass specifies the name of the class to be launched, not the filename or location.

Providing you have Java 11 installed (and JAVA_HOME is set at it), the JavaFX 11 SDK downloaded, and just following the getting started guide:

  • Download the HelloFX class to any location, i.e /Users/<user>/Downloads.

  • Open a terminal and cd to that location:

    cd /Users/<user>/Downloads
    
  • Set the JavaFX path:

    export PATH_TO_FX=/path/to/javafx-sdk-11/lib
    
  • Compile the class:

    javac --module-path $PATH_TO_FX --add-modules=javafx.controls HelloFX.java
    

    Check that HelloFX.class is created at the same folder level.

  • Run the class:

    java --module-path $PATH_TO_FX --add-modules=javafx.controls HelloFX
    

    It should run just fine.

Now, if you try to run the above command from a different location it won't work, because the HelloFX class is not available in the classpath.

So if you want to run this class from a different location you'll need to specify this classpath:

javac --module-path $PATH_TO_FX --add-modules=javafx.controls \
    /Users/<user>/Downloads/HelloFX.java

java --module-path $PATH_TO_FX --add-modules=javafx.controls \
   --class-path /Users/<user>/Downloads HelloFX

Upvotes: 4

Related Questions