Java

Create a GUI for your Java application with JavaFX

  • dani

dani

1 min read

If you come across Java GUI development, people tended to use Java Swing in the past. But Oracle is keen to replace Swing by JavaFX in Java 8. JavaFX allows separating the GUI layouting, the stylesheet and the Java source code (controllers).

The GUI can be layouted with FXML. The FXML files have to been in the classpath and each FXML file contains one so-called scene which in turn contains all UI elements. A scene in the content of a stage. Scenes can be implemented either in FXML directly (for experts/programmer) or using editor tools like Oracle's SceneBuilder (for designers). The SceneBuilder allows to create GUIs with drag and drop.

A good tutorial on how to create your first JavaFX project can be found at http://code.makery.ch/library/javafx-8-tutorial/. But the tutorial misses one important thing in my opinion: For easy Java dependency management we want to use Maven, so that we can integrate other projects into our JavaFX application. JavaFX normally uses Ant for the build. But there is a nice Maven plugin we can use: javafx-maven-plugin. The plugin allows you to build your JavaFX application with Maven on different platforms and with different outputs. You can add the Maven plugin as follows to your project:

<plugin>
 <groupId>com.zenjava</groupId>
 <artifactId>javafx-maven-plugin</artifactId>
 <version>8.1.4</version>
 <configuration>
 <mainClass></mainClass>
 <verbose>true</verbose>
 </configuration>
</plugin>

Another thing that would be neat is placing the FXML files in the standard path for resources src/main/resources. According to this question of stackoverflow we have three different opportunities to achieve that:

  • Put all of your fxml in the src/main/resources directory.
new FXMLLoader().load(getClass().getResource("/main.fxml");
  • Put all of your fxml in a src/main/resources/fxml directory.
new FXMLLoader().load(getClass().getResource("/fxml/main.fxml");
  • Place fxml in a corresponding resource directory; e.g. src/main/resources/com/mycompany/myapp.new
FXMLLoader().load(getClass().getResource("main.fxml");

As can be seen from the answer, only the way in which the FXMLLoader loads the files has to be changed.