Menu

Drombler Commons: Conventions to simplify FXML loading

Correctly loading a FXML file in JavaFX usually requires quite some boilerplate code.

In my projects I came up with a new naming convention:

If a class "mypackage.<name>" loads a FXML file, then the FXML file should be in the same package and be named "__<name>.fxml".

One advantage is, that when following this naming convention it's quite easy to see, which FXML loader/ fx:root-controller and FXML file belong together.

Another advantage is, that when using a utility method, the loading code for eg. a fx:root-based mypackage/MyPane.fxml file (a construct I can highly recommend) such as:

...
can be simplified to this:

package mypackage; import org.drombler.commons.fx.fxml.FXMLLoaders; ... public class MyPane extends SomePane { public MyPane() { FXMLLoaders.loadRoot(this); } ... }
This code will:

  • set the ClassLoader
  • set the root
  • set the controller
  • set the ResourceBundle by looking for a mypackage/MyPane.properties file (or a locale specific derivation using the default Locale)
  • set the location to mypackage/MyPane.fxml
  • load the mypackage/MyPane.fxml file
  • reduce code duplication 
  • reduce typos

The FXMLLoaders utility class provides several other utility methods taking advantage of this naming convention, such as utility methods for loading non-fx:root based FXML files, which then for a _mypackage/MyApplication.fxml _file such as:

...
can simplify the loading code to this:

package mypackage; import org.drombler.commons.fx.fxml.FXMLLoaders; ... public class MyApplication extends Application{ @Override public void start(Stage stage) { SomePane root = FXMLLoaders.load(getClass()); ... } }
Other variants allow to specify an alternative ResourceBundle or a pre-existing FXMLLoader.

The FXMLLoaders utility class is provided by the Drombler Commons - FX - Core artifact:

org.drombler.commons drombler-commons-fx-core 0.6
Like the other Drombler Commons artifacts, it can be used inside and outside of an OSGi environment.
link

Posted by SourceForge Robot 2015-06-16

Log in to post a comment.