Chart

JavaFX Graph Example

Photo of Andreas PomarolliAndreas PomarolliMarch 28th, 2016Last Updated: April 24th, 2019
0 293 7 minutes read

This is a JavaFX Scene Graph Example. A scene represents the visual contents of a stage. TheScene class in thejavafx.scene package represents aScene in a JavaFX program.

AScene object is attached to, at the most, oneStage at a time. If an already attached scene is attached to anotherStage, it is first detached from the previousStage. AStage can have, at the most, oneScene attached to it at any time.
 
 
 
 
 

 
The following table shows an overview of the whole article:

The following examples uses Java SE 7 and JavaFX 2.2.

1. What Is a Scene?

1.1 The Code

FxSceneGraphExample1.java

import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxSceneGraphExample1 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create the LabelLabel label = new Label("A Label");// Create the ButtonButton button = new Button("A Button");// Create the VBoxVBox root = new VBox();// Add the details to the VBox root.getChildren().addAll(label, button);// Set the vertical spacing between children to 10pxroot.setSpacing(10);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root,300,200);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A simple Scene Graph Example");// Display the Stagestage.show();}}

AScene contains a scene graph that consists of visual nodes. In this sense, aScene acts as a container for a scene graph. A scene graph is a tree data structure whose elements are known as nodes. Nodes in a scene graph form a parent-child hierarchical relationship. ANode in a scene graph is an instance of theNode class. A node can be a branchNode or a leafNode. A branchNode can have children nodes, whereas a leafNode cannot. The firstnode in a scene graph is called the rootnode. The rootnode can have children nodes.

AScene always has a rootNode. If the rootNode is resizable, for example, aRegion or aControl, it tracks the size of theScene. That is, if theScene is resized, the resizable rootNode resizes itself to fill the entireScene. Based on the policy of a rootNode, the scene graph may be laid out again when the size of theScene changes.

1.2 The GUI

The following image shows a very simple example of a Scene Graph. The Scene Graph only contains aLabel and aButton.

A simple Scene Graph Example
A simple Scene Graph Example

2. Setting the Cursor for a Scene

2.1 The Code

FxSceneGraphExample2.java

import javafx.application.Application;import javafx.scene.Cursor;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxSceneGraphExample2 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create the LabelLabel label = new Label("A Label");// Create the ButtonButton button = new Button("A Button");// Create the VBoxVBox root = new VBox();// Add the details to the VBox root.getChildren().addAll(label, button);// Set the vertical spacing between children to 10pxroot.setSpacing(10);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root,300,200);// Get the Hand cursor using its nameCursor cursor = Cursor.cursor("HAND");// Add the Cursor to the Scenescene.setCursor(cursor);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Cursor Example");// Display the Stagestage.show();}}

An instance of theCursor class represents a mouse cursor. TheCursor class contains many constants, for example,HAND,CLOSED_HAND,DEFAULT,TEXT,NONE,WAIT, for standard mouse cursors. The following snippet of code sets theHAND cursor for aScene:

// Create the SceneScene scene = new Scene(root,300,200);// Get the Hand cursor using its nameCursor cursor = Cursor.cursor("HAND");// Add the Cursor to the Scenescene.setCursor(cursor);

You can also create and set a custom cursor to aScene. Thecursor(String name) static method of theCursor class returns a standard cursor if the specified name is the name of a standard cursor.

2.2 The GUI

The following image shows an example of a Scene Graph using aCursor:

A Cursor in a Scene
A Cursor in a Scene

3. The Focus Owner in a Scene

3.1 The Code

FxSceneGraphExample3.java

import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.TextField;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxSceneGraphExample3 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create the LabelLabel label = new Label("A Label");// Create the ButtonButton button = new Button("A Button");// Create the TextFieldfinal TextField  text = new TextField("A TextField");// Add EventHandler to the Buttonbutton.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            text.requestFocus();            }        });// Create the VBoxVBox root = new VBox();// Add the details to the VBox root.getChildren().addAll(label, button, text);// Set the vertical spacing between children to 10pxroot.setSpacing(10);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root,300,200);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Focus Owner Example");// Display the Stagestage.show();}}

Only oneNode in ascene can be the focus owner. ThefocusOwner property of theScene class tracks theNode class that has the focus. Note that thefocusOwner property is read-only. If you want a specificNode in aScene to be the focus owner, you need to call therequestFocus() method of theNode class.

You can use thegetFocusOwner() method of theScene class to get the reference of the node having the focus in theScene. AScene may not have a focus owner, and in that case, thegetFocusOwner() method returns null. For example, aScene does not have a focus owner when it is created but is not attached to aWindow.

It is important to understand the distinction between a focus owner and a node having focus. EachScene may have a focus owner. For example, if you open two windows, you will have two scenes and you can have two focus owners. However, only one of the two focus owners can have the focus at a time. The focus owner of the active window will have the focus. To check if the focus owner node also has the focus, you need to use thefocused property of theNode class. The following snippet of code shows the typical logic in using the focus owner:

Want to master JavaFX ?
Subscribe to our newsletter and download theJavaFXProgramming Cookbookright now!
In order to get you prepared for your JavaFX development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

// Add EventHandler to the Buttonbutton.setOnAction(new EventHandler() {@Override public void handle(ActionEvent e) {text.requestFocus();}});

3.2 The GUI

The following image shows how the focus owner can be set in aScene. In our case, the click on theButton will do this action.

A Focus Owner Example
A Focus Owner Example

4. Using Builder Classes

4.1 The Code

FxSceneGraphExample4.java

package FXSceneGraph;import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.SceneBuilder;import javafx.scene.control.LabelBuilder;import javafx.scene.layout.VBox;import javafx.scene.layout.VBoxBuilder;import javafx.scene.paint.Color;import javafx.scene.shape.Rectangle;import javafx.scene.shape.RectangleBuilder;import javafx.stage.Stage;public class FxSceneGraphExample4 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Creating a blue RectangleRectangle rectangle1 = new Rectangle(10, 10, 20, 20);rectangle1.setFill(Color.BLUE);// Createing a green Rectangle by usage of a RectangleBuilderRectangle rectangle2 = RectangleBuilder.create().x(100).y(10).width(20).height(20).fill(Color.GREEN).build();// Create the RectangleBuilderRectangleBuilder builder = RectangleBuilder.create().width(20).height(20).fill(Color.RED);// Create two rectangles with the RectangleBuilderRectangle rectangle3 = builder.x(180).y(40).build();Rectangle rectangle4 = builder.x(120).y(20).build();// Create the VBox by usage of a VBoxBuilderVBox root = VBoxBuilder.create().children(LabelBuilder.create().text("A Scene Builder Example").build(),rectangle1,rectangle2,rectangle3,rectangle4).build();// Set the vertical spacing between children to 10pxroot.setSpacing(10);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the Scene by usage of a SceneBuilderScene scene = SceneBuilder.create().width(300).height(200).root(root).build();// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Scene Builder Example");// Display the Stagestage.show();}}

JavaFX provides two classes for creating and configuring objects that constitute the building blocks of a scene graph. One class is named after the type of object that the class represents. Another with the former class name suffixed with the word “Builder”. For example,Rectangle andRectangleBuilder classes exist to work with rectangles,Scene andSceneBuilder classes exist to work with scenes, and so on.

Builder classes provide three types of methods:

  • They have a create() static method to create an instance of the builder class.
  • They contain methods to set properties. Method names are the same as the property names that they set.
  • They have a build() method that returns the object of the class for which the builder class exists.

For example, thebuild() method of theRectangleBuilder class returns an object of theRectangle class. Builder classes are designed to use method chaining. Their methods to configure properties return the same builder instance.

The following snippet of code creates a rectangle, using theRectangle class, with(x, y) coordinates at(10, 20), with awidth of20px and aheight of20px. It also sets the fill property to blue:

// Creating a blue RectangleRectangle rectangle1 = new Rectangle(10, 10, 20, 20);rectangle1.setFill(Color.BLUE);

You can use theRectangleBuilder class to create a green rectangle:

// Createing a green Rectangle by usage of a RectangleBuilderRectangle rectangle2 = RectangleBuilder.create().x(100).y(10).width(20).height(20).fill(Color.GREEN).build();

Using builder classes requires longer code. However, it is more readable compared to using constructors to set the properties. Another advantage of builder classes is that they can be reused to build objects with slightly different properties. Suppose you want to create multiple rectangles with a 20px width and a 20px height, filled with the color red. However, they have different x and y coordinates. You can do so with the following code:

// Create the RectangleBuilderRectangleBuilder builder = RectangleBuilder.create().width(20).height(20).fill(Color.RED);// Create two rectangles with the RectangleBuilderRectangle rectangle3 = builder.x(180).y(40).build();Rectangle rectangle4 = builder.x(120).y(20).build();

4.2 The GUI

The last image shows how Scene Builder Classes ca be used to generate objects of different classes:

Using Scene Builder Classes
Using Scene Builder Classes

5. Download Java Source Code

This was an example ofjavafx.scene.

Download You can download the full source code of this example here:JavaFxSceneGraphExample.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Andreas PomarolliAndreas PomarolliMarch 28th, 2016Last Updated: April 24th, 2019
0 293 7 minutes read
Photo of Andreas Pomarolli

Andreas Pomarolli

Andreas has graduated from Computer Science and Bioinformatics at the University of Linz. During his studies he has been involved with a large number of research projects ranging from software engineering to data engineering and at least web engineering. His scientific focus includes the areas of software engineering, data engineering, web engineering and project management. He currently works as a software engineer in the IT sector where he is mainly involved with projects based on Java, Databases and Web Technologies.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.