CodeNewbie Community 🌱

Cover image for JavaFX: A Brief Introduction (Part One)
Miguel Manjarres
Miguel Manjarres

Posted on

JavaFX: A Brief Introduction (Part One)

Introduction

If you have been developing in Java for a while you may have heard about Java Swing, the native Java GUI library, which you can use to build user interfaces. Using JSwing is great but wouldn't be nice if you could...

  • Style your components using CSS like you would with HTML?
  • Use the MVC pattern when building your interfaces?
  • Embed web content in your apps?

If your answers to these questions is yes then JavaFX is the right choice for you! Stay with me if you want to know what JavaFX is, what is the structure of a JavaFX project and how to build your first app.

What is JavaFX?

First of all, JavaFX isn't as old as JSwing, but it isn't brand new either, it came out in 2009 and has been growing ever since, with version 15 being the latest version released and version 16 being just around the corner.

According to Oracle, JavaFX is a development platform for building desktop apps using graphics, animations, transitions and so on, is intended to replace JSwing as the standard GUI library for Java (so good thing you are learning it huh?). Since version 11 of the JDK came out in 2018, Oracle made JavaFX part of the OpenJDK project under the un-creative name of OpenJFX.

So, that's the what, now let's focus on the how. How can you build something with JavaFX? First you need to learn some new concepts that weren't present when working with JSwing.

Concepts

JavaFX uses some of the concepts of theatrical performance to name the components of it's architecture. Not sure what I mean? Let's begin.

Stage

The stage is the top level JavaFX container, and it often refers to the window itself. Think of it as an actual stage where the play takes act.

Scene

The scene is the local JavaFX container and it refers to the actual views of your application. Think of it as the background elements of a play, they bring life to the stage and change from time to time depending of what is needed.

These scenes are actually FXML files (FXML is markup language similar to XML) that you can construct using any text editor, but you can guess how boring would that be. Luckily for us there are tools that let us drag and drop components just like we would do in JSwing (more of that later).

Nodes

So we have the stage, the scenes, what else do we need? Hmm... that's right! The actors! They are responsible for making the actual play. In JavaFX, these actors are the nodes, and they refer to the GUI elements like buttons, panels, lists and so on. As a matter of fact, every GUI component extends from the Node class.

Building Scenes with Scene Builder

I mentioned early that the way you build the views AKA the scenes of your applications is by creating FXML files.

These files look something like this:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>


<GridPane fx:controller="fxmlexample.FXMLExampleController" xmlns:fx="http://javafx.com/fxml" alignment="center" styleClass="root">
  ...
</GridPane>
Enter fullscreen mode Exit fullscreen mode

In this example GridPane is the root layout but note that is it not mandatory to use it everytime, there's a couple of layouts you can use to organize your components.

From there you could start to add more elements, just like you would do in regular HTML, but you can see this would be very time consuming, that's why Scene Builder was created.

Scene Builder is a "visual layout tool that lets users quickly design JavaFX application user interfaces, without coding". In other words, is a tool that let's you generate FXML files (views) in a visual way by dragging and dropping components in your base layout.

sb_example

Go ahead and download Scene Builder if you want to dive with me in a practical example, you'll see how easy it is to edit scenes with this tool!

A Practical Example

Enough theory, let's begin developing shall we?

(Side note: I'm assuming you are using JDK 8. JavaFX is no longer bundled in JDK version 9 and up so if that's your case, you need to download the JAR file and add it to your project PATH)

I will be using IntelliJ but the steps are somewhat similiar in NetBeans.

Open your IDE and create a new project, you will be prompted to select which type of project do you want, select JavaFX.

img_tuto_1

After a few seconds you should have a freshly new JavaFX project. Before going further, let's run int and see what we have.

img_tuto_2

We got a nice looking window saying "Hello Wold" on the title. Nothing too fancy just yet. But how did that window pop out into existence?

Let's take a look at out Main class and see what's going on...

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        // Step 1
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

        // Step 2
        primaryStage.setTitle("Hello World");

        // Step 3
        primaryStage.setScene(new Scene(root, 300, 275));

        // Step 4
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}
Enter fullscreen mode Exit fullscreen mode

First we notice that the Main class extends from the Application class, that's interesting.

Second we go to the main method and see that it calls the launch method. Now we don't actually see it but this method is defined within the Application class, and it's responsible for initializing our app. Later on when everything has been set, it actually starts the app by calling the start method, yes, the one we are overriding here. Let's take a closer look.

The start method receives an argument called primaryStage of type Stage, sound familiar? This is the window we see that it pops out! But how do we put content in there?

  • Step One: First we need to load the view, that is, the FXML file into memory. We do this by using the load method of the FXMLLoader class.

  • Step Two: We assign our window a title.

  • Step Three: Remember, the stage is just an empty place, it needs to be filled with something and in this step we are filling it with a new scene using the setScene method. We pass it a new Scene in which we pass the content of our view (our FXML file) as well as some custom dimensions. (Note: These dimensions are not mandatory, if you dont't specify them it will default to the values present in the FXML file).

  • Step Four: Initially all stages have their curtains down, we need to show them! We do this by using the show method (kinda reminiscing of the JSwing library).

And that's it! It wasn't so bad was it?

(Side note: These steps are just a placeholder. You don't need to do it in this exact order!)

Now let's take a look at the project folder structure:

img_tuto_3

Nothing too fancy here but note there's a Controller class there. Every scene you create needs a Controller. The controller is responsible for handling things like events, inputs, outputs and so on.

One of the advantages of building apps with JavaFX is that the presentation layer and the logic layer are not tigthly coupled. The controller can function any scene and visceversa as we can always abstract the components we use.

The way we tell our view which controller to use is with the fx:controller property. Go and double-click the sample.fxml file, you'll see this property has already been set for you:

<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<GridPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
</GridPane>
Enter fullscreen mode Exit fullscreen mode

It's important to note here that the path is relative to the root package, in this case, sample.

Let's move on and edit this view! If you downloaded Scene Builder you'll see that when you right-click the sample.fxml file, there's an option called "Open with Scene Builder" at the bottom. (If you are on NetBeans it automatically opens it when you double-click it).

img_tuto_4

When you open it you will see there's a panel with the title of "Document" and below that there's the "Hierarchy". This list contains the node tree of our application.

Let's begin by deleting the GridPane element and replacing it with an AnchorPane (you can look up the element by typing its name in the search bar). When you got it just drag it and drop it in the middle of the screen.

Next you will see on your right a new panel called "Inspector". In this panel you can edit all the properties of your elements. In this case we will edit the width and height of our Anchor Pane (since this is our root element, these numbers will define the dimension of our window). You can put the numbers you like, I'll put 200 x 200.

img_tuto_5

Nice! Now we have our scene ready, let's put some actors in!

We will do so in the next part of this post. Thank you so much for reading this far. If you have comments please leave them down below.

See you next time 👋.

Top comments (2)

Collapse
 
bhateanuradha profile image
Anuradha Rajendra Bhate

JAVA Classes in Pune
JAVA Course in Pune
JAVA Training in Pune

As a programmer, you must take challenges to continue to exist and construct some wonders in the improvement or programming field. Hence, if you are in search of to examine an superior programming language to beautify your profession skills, Java is one of the exceptional potentialities around.

To boost skills, you ought to continuously enhance your strategies. In current times, Java has end up one of the most famous languages for developers. From the net to Windows, Java has its uniqueness on one-of-a-kind platforms.

The availability of severa assets and structures to examine Java can also make you puzzled about the gaining knowledge of curve. Therefore, let's find out the nice Java blogs that can help you in reaching your objective.

Firstly, Java is one of the most readable and handy to write programming languages. Therefore, even in this decade, the incidence of Java is always expanding.

Secondly, Java is an object-oriented, high-level programming language. The syntax of Java is comparable to C and C++. Hence, it has come to be one of the most beginner-friendly programming languages out there.

Thirdly, with its superior reminiscence allocation and built-in tools, Java presents portability and versatility. Another exceptional factor about Java is that most of its points are open-source. Therefore, it is beneficial for beginner-level or small projects.

Lastly, Java continuously updates its points with its API and EE (Enterprise Edition), making it extra accessible, compulsive, and efficient.

Another incredible neighborhood of Java is Java Code Geeks. It's an unbiased on-line platform of Java that presents severa tutorials, courses, examples, mini-books, SOA, agile, and resources.

Moreover, it has a code geek community area for Java concentrated on Java architects, senior and junior developers, technical and small projects, and more.

Java Code Geeks additionally has an interesting "Best of the week" part with the weekly launched Java updates.

sevenmentor.com/java-training-clas...

Collapse
 
iteducationcentre1 profile image
iteducationcentre1

Nice blog. Thanks for sharing.
Java training in Pune