JavaFX 2.0 Hello World

Before talking about the example itself, I want to show you how to create a JavaFX application in NetBeans. (If you haven´t installed JavaFX and NetBeans yet, please see my previous post Installing JavaFX 2.0 and NetBeans 7.7.1) Click on “New Project” in the “File” menu to open the project wizard. Then choose “JavaFX->JavaFX Application” and press “Next”.

In the next dialog you can specify the name of your application and a destination folder, where it should be stored. If you have installed JavaFX correctly the “JavaFX Platform” should be specified already. Otherwise you can add the platform yourself by clicking on “Manage Platforms->Add Platform” and specifying the paths to your JavaFX installation.

Note: By default the “Create Application Class” checkbox is checked. Please uncheck it because we´ll create our own application class.
Click on “finish” to create your first JavaFX application.

Hello World in JavaFX 2.0 – Example 1

Probably every single software developer knows the famous „HelloWorld“ example as it is often used to show the syntax of a (unknown) programming language and to give a first clue, of what the language looks like. I don´t want to break this tradition, so here are 2 different versions of a HelloWorld program in JavaFX 2.0. I´ll show the complete code first and then explain the individual parts.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * 
 * Created on: 17.03.2012
 * @author Sebastian Damm
 */
public class HelloJavaFX extends Application
{
    @Override
    public void start(Stage stage) throws Exception
    {        
        Button bt = new Button('Print HelloWorld');
        bt.setOnAction(new EventHandler<ActionEvent>() 
        {
            @Override
            public void handle(ActionEvent arg0)
            {
                System.out.println('HelloWorld! :)');
            }
        });
        
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 300, 150);
        root.getChildren().add(bt);

        stage.setTitle('HelloWorld in JavaFX 2.0');
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args)
    {
        Application.launch(args);
    }
}

The first thing worth mentioning is that you have to extend from the Application class in order to create a working JavaFX application. This class provides several live-cycle methods and is the starting point for your application. It is an abstract class (which means, that you cannot instantiate it) with a single abstract method start, that you have to override. You are provided a stage object by the JavaFX runtime, which you can use to display your UI.


To start your application you have to call the static method launch as seen in the main method in this example. After launching your application, it will call the start method. Here is the JavaDoc of the Application class, which shows the individual steps when starting a JavaFX application.
The entry point for JavaFX applications is the Application class. The JavaFX runtime does the following, in order, whenever an application is launched: Constructs an instance of the specified Application class

  • Calls the init() method
  • Calls the start(javafx.stage.Stage) method
  • Waits for the application to finish, which happens either when the last window has been closed, or the application calls Platform.exit()
  • Calls the stop() method

Let´s start with the real source code inside the start method.
First of all we create a simple Button and specify an action to be triggered when the button is clicked via the setOnAction method (compare JButton´s addActionListener).
Next we create a StackPane object, which is one of the layout panes in JavaFX (One of the next blog posts will cover all different layout panes in JavaFX). I use a StackPane here, because it automatically takes all the available space provided by its surrounding parent and because it automatically centers its children inside.

Note: The foundation of a JavaFX application is the Scene graph. Every single Node (which includes simple controls, groups and layout panes) is part of a hierarchical tree of nodes, which is called the Scene graph. The Scene graph and therefore your whole JavaFX application has always one single root node!

As mentioned above, the start method has a Stage object parameter, which is provided by the JavaFX runtime. This Stage object is a kind of window. You have to give it a Scene object as its viewable content. You can create a Scene object by passing the root node of your application. Optional parameters are the width and the height of your scene as well as a Paint object, which includes simple colors and also complex color gradients.
With root.getChildren().add(bt); you add the button to your root node, which is a stackpane.
After that we set a title to the stage and apply the created scene object. Finally with the show method we tell the stage to show. (compare Swing´s setVisible

Now your application should look like this:

And it should print ‘HelloWorld’ to the command line if you click the button. Nothing spectacular yet, but it´s your first working JavaFX application, so congratulations! :)

Hello World in JavaFX 2.0 – Example 2

Additionally a slightly changed example, which will show the text in the GUI.
The code:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * 
 * Created on: 17.03.2012
 * @author Sebastian Damm
 */
public class HelloJavaFX2 extends Application
{
    @Override
    public void start(Stage stage) throws Exception
    {
        final Group root = new Group();
        Scene scene = new Scene(root, 500, 200, Color.DODGERBLUE);
        
        final Text text = new Text(140, 120, 'Hello JavaFX 2.0!');
        text.setFont(Font.font('Calibri', 35));
        text.setFill(Color.WHITE);
        text.setEffect(new DropShadow());        
        
        Button bt = new Button('Show HelloWorld');     
        bt.setLayoutX(180);
        bt.setLayoutY(50);
        bt.setOnAction(new EventHandler<ActionEvent>() 
        {
            @Override
            public void handle(ActionEvent arg0)
            {
                root.getChildren().add(text);
            }
        });

        root.getChildren().add(bt);
        
        stage.setTitle('HelloWorld in JavaFX 2.0');
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args)
    {
        Application.launch(args);
    }
}

Instead of using a layout pane we use a Group object here. Group is a subclass of Parent (which is a subclass of Node) and takes one or more children. A Group isn´t directly resizable and you can add transformations or effects to a Group which will then affect all children of the Group. (Note that we now also provided a Paint for the Scene.)
Next we create a Text object. Because we have no layout pane, we specify the x and y coordinates directly. We specify a custom font, change the color to white and add a DropShadow.
The Button also gets coordinates and instead of printing “HelloWorld” to the command line when we click the button, we add the created Text object to our root element (and therefore to the Scene Graph).
After clicking the button, your application shoul look like this.

Summary:

  • A JavaFX Stage object is a kind of window and behaves similar to a JFrame or JDialog in Swing.
  • A JavaFX Scene object is the viewable content of a Stage and has a single Parent root node.
  • Node is one of the most important classes in JavaFX. Every control or layout pane is a kind of node.
  • The Scene Graph is a hierarchical tree of nodes. It has one single root node and is the foundation of your application. It has to be passed to a Scene object
  • In order to create and start a JavaFX application you have to complete the following steps:
    • Extend the Application class
    • Override the abstract start method
    • Create a root node and add some elements to it
    • Create a Scene object and pass the root node to it
    • Apply the Scene to the Stage via setScene
    • Tell the Stage to show with the show method
    • Call Application.launch in your main method

Reference: Hello World in JavaFX 2.0 from our JCG partner Sebastian Damm at the Just my 2 cents about Java blog.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Leave a Reply


× 7 = fifty six



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books