Imagine a bacon-wrapped Ferrari. Still not better than our free technical reports.
See all our reports

Why I’m so excited about migrating from Swing to JavaFX 2

Yep, another article on JavaFX

Ok, I know what you’re thinking: “Oh, another JavaFX technical article”. You’re right. This is an article about how JavaFX is the best thing since bacon-wrapped Ferraris.

JavaFX

I’ve been thinking recently about what JavaFX brought to me as developer, and earlier this year I gave a presentation at MarsJUG in Marseille and FinistJUG in Brest on the topic (see the slides above). See, I come from the Java EE world, meaning I do a lot of EJBs, JPA and so on. But also a lot of JSF. Years ago, I also did Swing development, and even managed to enjoy it most of the time. So I have to deal with core/business classes but also with UI and UX.

I got seduced by JavaFX 2 at Devoxx France 2012 I went to a presentation by guys from Oracle. I was very disappointed by JavaFX 1 but I decided to give it a try.

I decided to develop an app to test JavaFX 2 and I discovered that it covers a lot of concepts from JEE: the binding, the controllers. But also concepts brought by Qt years ago: building a UI with an XML file. For me it is the really first time we can do real MVC for Java desktop apps. It was very freeing for a guy like me, who is normally pretty strict with architectures. When you’re playing with all of this, it is very convenient and natural (even if you have to forget your old Swing tricks).

Why should you bother with JavaFX?

You may ask “Why trying something else to create UI, and why JavaFX?”. That’s a great question. First of all, I’m always looking for new technologies to be up to date in terms of knowledge. I also strongly believe in desktop apps. Nowadays, everyone is talking about web technologies (Angular.js, jQuery, etc) probably because everyone is disappointed with desktop app development; but I don’t think desktop apps are dead. Historically in Java it was difficult to quickly create a sexy UI in Swing, which is a problem by itself. Users want apps quickly, and it is here where my passion for JavaFX started.

The way of developing software changes. Developers change. Languages change. Practices change. So it goes for Java. For more than a decade, we used Swing in order to create our UIs, with all the difficulties it implies. The way of creating UIs had to change in order to be easier and more flexible, which is exactly where JavaFX brings some new fresh air to the world of Java desktop development.

What sucked about Swing that JavaFX improves

Using Java classes for modeling and creating a UI is not really MVC-oriented. In Swing, you often create a class that extends JFrame in order to create your view. And then you add all possible controls your UI will need.

What you may also do is use your IDE (with some plugins) to create your UI by dragging and dropping your components from a palette to a build area. And then the code is generated for you. The big disadvantage is that this code may not be difficult to understand or not adapted to your practices, so to maintain it a lot of junk code is potentially generated.

In JavaFX 2 things change. Now you have FXML files that are used to create the UI. But what is a FXML file? It is a kind of XML that will contain all the controls of your UI.

<?xml version="1.0" encoding="UTF-8"?>
 
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
 
<AnchorPane id="AnchorPane" prefHeight="101.0" prefWidth="586.0" xmlns:fx="http://javafx.com/fxml">
  <children>
    <Label layoutX="14.0" layoutY="14.0" text="File" />
    <TextField layoutX="44.0" layoutY="11.0" prefWidth="200.0" />
    <Button layoutX="252.0" layoutY="12.0" text="..." />
    <GridPane layoutX="373.0" layoutY="11.0">
      <children>
        <Label text="Red:" GridPane.columnIndex="0" GridPane.rowIndex="0" />
        <Label text="Green:" GridPane.columnIndex="0" GridPane.rowIndex="1" />
        <Label text="Blue:" GridPane.columnIndex="0" GridPane.rowIndex="2" />
        <Slider max="1.0" GridPane.columnIndex="1" GridPane.rowIndex="0" />
        <Slider max="1.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
        <Slider max="1.0" GridPane.columnIndex="1" GridPane.rowIndex="2" />
      </children>
    </GridPane>
    <Button layoutX="291.0" layoutY="12.0" mnemonicParsing="false" onAction="loadFile" text="Load" />
  </children>
</AnchorPane>

In that example you can notice some things:

  • there are some imports like in a Java class
  • there is no Java code
  • it is pretty simple to understand

This is good news. Indeed, this means you are able to create a view without typing a single line of Java code and it is totally MVC-oriented.

With FXML you can also customize your controls by using CSS:

And if you would like to use stylesheets? It is also supported:

<AnchorPane>
	<stylesheets>
		<URL value=”@/com/rebellabs/jfx/css/Default.css” />
	</stylesheets>
 
	<Label text=”Hello RebelLabs” styleClass=”title” />
</AnchorPane>

Great, isn’t it?

Properties and binding

How many times would you like to have been notified when a element was added in a list? Or when the value of a String changes? The Observer/Observable pattern is a solution, but it has to be triggered manually in each situation you would like to update it.

In JavaFX 2, things can be done automatically because a new type of object is available: Properties. A property encapsulates a Java type: String, int, boolean etc, and can have listeners.

For example, there is a StringProperty class for working on Strings, IntegerProperty, BooleanProperty and many more. But you also have the generic ObjectProperty, so that you can encapsulate your own Java object. Let’s take a look how to add a listener to a property:

ObjectProperty<RebelFolk> rebelGeek = new SimpleObjectProperty<>();
rebelGeek.addListener(new ChangeListener<RebelGeek>() {
            @Override
            public void changed(ObservableValue<? extends RebelGeek> observableValue, RebelGeek oldValue, RebelGeek newValue) {
                // Do awesome things
            }
        }
);

Nothing more, nothing less. Each time the value of the property changes, the listener is triggered. What can also be done is bind properties together:

rebelGeek.bind(anotherRebelGeek);

Each time the anotherRebelGeek value changes, rebelGeek will be updated with the new value. Look at this another binding example:

IntegerProperty num1 = new SimpleIntegerProperty(10);
IntegerProperty num2 = new SimpleIntegerProperty(20);
IntegerProperty num3 = new SimpleIntegerProperty(30);
IntegerProperty num4 = new SimpleIntegerProperty(40);
 
NumberBinding operation = Bindings.add(num1.multiply(num4), num2.divide(num3));
System.out.println("How much? " + operation.getValue());
 
num1.setValue(100);
System.out.println("And now? " + operation.getValue());

This will first display 400.67 then 4000.67. Magical isn’t it? So you easily imagine some use cases: resizing a window will resize its elements, typing in a text field will display the conversion from $ to €, etc.

Other cool stuff

There is more than what we’ve already mentioned that are interesting in JavaFX:

  • A chart API is available so that you can create, customize and interact with charts. They are dynamically updated when the data set changes.
  • A media engine allowing you to play songs and video. It is a long way from JMF; streaming is also supported.
  • A web engine providing a full browser based on WebKit will allow you to display web content directly in your app.
  • ImageOps allows you to directly work with image to manipulate their properties and pixels.
  • Creating custom components is easy and allows you to either extend existing controls or create brand new ones in order to fulfill your needs.
  • And in JavaFX 8 (coming with Java 8) you will also have the 3D support–but this is for later ;)

Rapid Application Development with JavaFX

I think a great evolution in Java app development is the possibility to easily customize the UI you’re creating. To be honest, Swing was horrible at natively customizing the components you were using. You had libraries to modify the look and feel but what about corporate UI (in which you have to integrate your company fonts, design and so on)?

In JavaFX, everything is customizable using JavaFX CSS: it is not CSS like you know it in web development, but it’s very similar. You don’t have to write any Java code (in most cases) to change the look and feel of your app and it can be done really quickly. This is really progressive, and if you want to go further you can create your own components from scratch or extending existing ones. For example, if you would like to create a search field with a text field and a search button just next to it you can create a custom component adding a text field and a button and use CSS to customize them.

Ultimately, JavaFX provides you with more tools to do RAD (Rapid Application Development):

  • SceneBuilder allows you to create your UI by drag and dropping components on a scene and then generate the FXML file. You have a CSS previewer built in to see what your CSS looks like.
  • ScenicView allows you to manipulate the components while your app is running. It is very useful to modify the CSS and see the result on the fly before applying it in your code.

Conclusion

JavaFX is the successor of Swing, which will be deprecated, and even though it is still young it will help you a lot. It changes the way we do UI in Java by bringing new concepts, plus it’s easy to learn and use and even fun to try out. As Java developer for many years, JavaFX is a huge step forward for developing desktop apps in Java. But don’t take my word for it–test it yourself!

I’m happy to see your comments below, or tweet your thoughts at @twasyl or @RebelLabs.