JavaFX can be written using a strong separation of presentation and business logic. That’s great for big projects that require it. However, sometimes it is nice to write an application completely in Java.
After all, if you are a Java developer, and just need a quick UI for a tool that isn’t going to be used by anyone but you, you don’t want to fuss around with FXML, CSS, annotations, and dependency injection. When you just want a custom dialog, all that extra work gets in the way.
Never fear! JavaFX allows pure Java implementations as well as the fancier FXML/CSS implementations.
Let’s create an example in Eclipse (or your favorite JavaFX friendly IDE) create a new Java project. Nothing fancy is needed for your JavaFX project. Just a standard Java project that supports Java 7 or above.
Create a class named SimpleFXExample in the package com.whatisjavafx. Modify your new JavaFX app’s code to read as follows.
If you are using Eclipse to do your JavaFX development, there is a chance you’ll run into an access restriction with JavaFX (and more specifically with using jfxrt.jar.) This is easily cleared up.
Find the project preferences. This will be different places depending on your OS. On Windows, it is under the Windows menu.
Under the preference dialog, navigate to the Java -> Compiler -> Errors/Warnings section and change the forbidden reference rule from exception to ignore. That should allow you to compile JavaFX programs without an issue.
It may be easier just to copy the jfxrt.jar JAR to a folder in your project, and then include the JAR in your project’s build path. That makes code completion for JavaFX available, and that makes everyone’s day just a little better.
Getting back to your program … Your JavaFX program doesn’t do anything yet, but we’ll get to that shortly. You are well on your way to understanding what JavaFX is.
You are extending the javafx.application.Application class. That is the base class for every JavaFX application. Instead of starting your application in the main() method, JavaFX applications start in the start() method. A one liner is added to the main() method to launch the JavaFX application and then the real starting method is the start() method.
Next, lets put something useful in the start method.
Running this JavaFX app will result in a small window that say’s hello world. That’s a pretty simple, first JavaFX sample hello world app.
You can easily build on that example to get a much more complex pure Java JavaFX UI.