JavaFX Series (PART 2) – Creating a Hello World Application

JavaFX

Welcome to the 2nd part of my JavaFX Series, In this tutorial we will be creating a Hello World program. Before we go on to the coding part, Lets understand some basic concepts.

Our JavaFX GUI is powered by JavaFX Scene Graph API, The Scene Graph API allows us to produce complex animations and effects in our GUI. There are 3 important things:

  1. Stage

  2. Scene

  3. Root Node

The most important part of our application is the Stage, The Stage is the main container. It’s just like a Window except it’s empty but has borders and the Minimize, Maximize and Close button, something like this:

Stage (Main Container)

The Stage looks boring initially because there are no elements in it like the Button, Labels etc.  Before going further, lets write the code for the Stage.

Start NetBeans and Create a  new JavaFX Application project.

Stage Setting

Once you have created the Project, create a new Package and name it whatever you want, for this tutorial I’ve named it fxseries. 

After this, create a new Java Class inside the package that we just created and name it FxmlMain. Then create a new Empty FXML file under JavaFX inside the same Package. I’ve named the file as SceneAlpha. After you name the file, we now have to connect it with the controller file so just tick the Use Java Controller and it’ll automatically create a new controller file for your FXML File, Now press finish.

FXML

After the above step, your project will have 3 files:

Files

So what are the purpose of these files? I mean what does the main file do, what’s the function of the controller and why did we create that Fxml File? Lets go through them one by one,

Main Class

The only purpose of the main class is to launch your application, the stage that you saw earlier (Empty one) is the result of this class. You’ll understand this when we’ll write the code.

FXML File

This is the view, your Front End. The FXML file contains your UI elements, Buttons, Labels, etc. As I said in the previous tutorial that we don’t have to touch this file, The SceneBuilder that we setup earlier will take care of this file.

Controller Class

The controller class is all about handling the user interaction with our GUI like clicking buttons. When you click a Button, a response is generated based on the code inside the respective controller.

Time to write the code to make the Stage happen, So just open the FxmlMain.java file and TYPE the following code:


import javafx.application.Application;
import javafx.stage.Stage;

/**
*
* @author Ex094
*/
public class FxmlMain extends Application {

@Override
public void start(Stage stage) throws Exception {

//Sets the Title of the Stage Window
stage.setTitle("JavaFX Series Stage");

//Sets the visibility of the Stage to True so it can be displayed
stage.show();
}

public static void main(String[] args) {

launch(args);

}
}

I’ve mentioned comments in the code so that it’s clear to you what each line of code does, Now it’s time to run the code so press F11 to build and then press F6 to run and you’ll see the Windows pop up which is basically our stage.

Time to add some UI Elements to our dull and boring Stage, So in your project (Supposing you’ve setup Scene Builder with NetBeans from Part 1 of this series) double click on the SceneAlpha.fxml. Well add a Button and a Label, and we will remove the text from the label, It’ll look something like this:Scene Alpha Setup

To make the Label empty, Just leave the Text Property of the Label blank, Lets test our GUI now. Press Ctrl + S to save your progress and go back to NetBeans (You can keep Scene Builder Open) and Run your project.

Whoops!! What have we done wrong, you’ll probably notice we’ve got the same old boring windows appearing like this

Stage (Main Container)

Well that is because we did associate a Scene with our Stage. The Scene in turn contains all the JavaFX nodes. Think of the Scene as a kind of Projector, it projects your fxml on to your Stage. After adding the Scene we get:

Associate Scene

Yay 😀 So lets change the previous code in order to add the Scene and then assign it to the Stage.

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

/**
 *
 * @author Ex094
 */
public class FxmlMain extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        
        //Load Root layout from the FXML file
        Parent root = FXMLLoader.load(getClass().getResource("SceneAlpha.fxml"));
        
        //Link FXML file with the Scene that will project it to the Stage
        Scene alpha = new Scene(root);
        
        //Set Stage Window Title
        stage.setTitle("JavaFX Series Stage");
        
        //Set the Scene
        stage.setScene(alpha);
        
        //Set the Stage visible
        stage.show();
    }
    
    public static void main(String[] args) {
        
        launch(args);
        
    }
}

After the above step our view is ready but the thing is if you press the button, nothing will happen. That’s because we haven’t taken care of our events i.e. if the button is pressed, change the label text to “Hello World”. We handle our events in the Controller file and you might recall that we made one for our scene earlier in this tutorial.

Open the SceneAlphaController.java file that we made earlier, Now in order to handle events for the button i.e on Click, we need to have a reference to that button. It’s not like the code will automatically know that which button in the FXML file we are going to handle the event. So we need to give our UI elements some ID so that we can reference them in our code. Here’s the code to add the reference for your UI Element:

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;

/**
 * FXML Controller class
 *
 * @author Ex094
 */
public class SceneAlphaController implements Initializable {
    
    //Reference to our Button with the ID button
    @FXML
    private Button button;
    
    //Reference to our Label with the ID label
    @FXML
    private Label label;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }       
}

After you’ve done writing the code above, don’t forget to save your project. Go back to your scene builder, Select your Button, on the Right side there are some accordions (Properties, Layout and Code). Press the Code, for this tutorial we are concerned with the property fx:id under the Identity. Click the Arrow besides the Textbox and select button. This is the same name that we recently has declared in our Controller code. Do the same for the Label.

Setting Element ID

 

We are now done connecting our elements with our code, now it’s time to handle the ButtonClick even of our button. So open your SceneAlphaController.java and type this code in the Initialize method

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;

/**
 * FXML Controller class
 *
 * @author Ex094
 */
public class SceneAlphaController implements Initializable {
    
    //Reference to our Button with the ID button
    @FXML
    private Button button;
    
    //Reference to our Label with the ID label
    @FXML
    private Label label;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //On button click
        button.setOnAction((e) -> {
            //Set the Label text to Hello World
            label.setText("Hello World!");
        });
    }    
}

That code inside that we just introduced is a Lambda Expression, There are other ways to handle events including Method References which makes our code like this:

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;

/**
 * FXML Controller class
 *
 * @author Ex094
 */
public class SceneAlphaController implements Initializable {
    
    //Reference to our Button with the ID button
    @FXML
    private Button button;
    
    //Reference to our Label with the ID label
    @FXML
    private Label label;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //TODO
    }
    @FXML
    private void handleButtonAction(ActionEvent event) throws IOException {
        label.setText("Hello World");
    }
}

You see we have introduced a new method called HandleButtonAction, and inside it we have a line of code which will change the text of the label. Now all we have to do is link the method to the button and for that just save your project and go back to scene builder, select our Button and then goto the Code accordion again.  There you’ll see a selector for On Action, press the arrow and select your method that you just created i.e HandleButtonAction.

Method Reference

Both cases will work but I’ll stick to Lambda Expressions. Now save and build your project then press F6 to run. Press the Hello button and see the magic happen 😀

Hello World App

Congrats!! You just made your own Hello World program in JavaFX 😀 I recommend tinkering more with your new application in order to learn, try to add more elements and link them up. Explore the Scene Builder.

This is the end of Part 2, I’ll be writing up Part 3 so stay tuned 🙂
Regards,
Ex094

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s