0% found this document useful (0 votes)
24 views93 pages

Cs3391 Oops Unit V

OOPS

Uploaded by

hm0401234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views93 pages

Cs3391 Oops Unit V

OOPS

Uploaded by

hm0401234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

UNIT V

JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS

JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events. Controls: Checkbox,
ToggleButton – RadioButtons – ListView – ComboBox – ChoiceBox – Text Controls – ScrollPane. Layouts –
FlowPane – HBox and VBox – BorderPane – StackPane – GridPane. Menus – Basics – Menu – Menu bars –
MenuItem.

1. JAVAFX Events and Controls: Event Basics

1.1 Introduction
JavaFX is a Java library used to build Rich Internet Applications. The applications written using this library
can run consistently across multiple platforms. The applications developed using JavaFX can run on
various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.
To develop GUI Applications using Java programming language, the programmers rely on libraries such
as Advanced Windowing Toolkit and Swing. After the advent of JavaFX, these Java programmers can
now develop GUI applications effectively with rich content.

Need for JavaFX

• To develop Client Side Applications with rich features, the programmers used to depend on
various libraries to add features such as Media, UI controls, Web, 2D and 3D, etc.
• JavaFX includes all these features in a single library. In addition to these, the developers can also
access the existing features of a Java library such as Swing.
• JavaFX provides a rich set of graphics and media API’s and it leverages the modern Graphical
Processing Unit through hardware accelerated graphics.
• JavaFX also provides interfaces using which developers can combine graphics animation and UI
control.

Features of JavaFX

Feature Description
Java Library It is a Java library which consists of many classes and interfaces that are
written in Java.
FXML FXML is the XML based Declarative mark up language. The coding can be
done in FXML to provide the more enhanced GUI to the user.
Scene Builder Scene Builder generates FXML mark-up which can be ported to an IDE.
Web view Web pages can be embedded with JavaFX applications. Web View uses
WebKitHTML technology to embed web pages.
Built in UI controls JavaFX contains Built-in components which are not dependent on
operating system. The UI component are just enough to develop a full
featured application.
CSS like styling JavaFX code can be embedded with the CSS to improve the style of the
application. We can enhance the view of our application with the simple
knowledge of CSS.
Swing interoperability The JavaFX applications can be embedded with swing code using the
Swing Node class. We can update the existing swing application with the
powerful features of JavaFX.
Canvas API Canvas API provides the methods for drawing directly in an area of a
JavaFX scene.
Rich Set of APIs JavaFX provides a rich set of API's to develop GUI applications.
Integrated Graphics An integrated set of classes are provided to deal with 2D and 3D
Library graphics.
Graphics Pipeline JavaFX graphics are based on Graphics rendered pipeline(prism). It offers
smooth graphics which are hardware accelerated.
High Performance Media The media pipeline supports the playback of web multimedia on a low
Engine latency. It is based on a Gstreamer Multimedia framework.
Self-contained Self Contained application packages have all of the application resources
application deployment and a private copy of Java and JavaFX Runtime.
model

JavaFX Architecture

The following image shows the complete architecture of JavaFX platform. There are various built-in
components which are interconnected with each other. However, JavaFX contains a rich set of APIs which
are more than enough to develop rich internet applications which run consistently across many platforms.
JavaFX public API

The top layer of JavaFX architecture contains a JavaFX public API which provides all the necessary classes
that are responsible for executing a full featured JavaFX application. The list of all the packages of this API
are as follows.

Package Name Description


javafx.animation Provides the set of classes that are responsible for transitions based
animations
javafx.application Provides application life-cycle methods
javafx.collections Provides classes that can handle collections and related utilities
javafx.concurrent Provides classes that are responsible for multitasking
javafx.embed.swing Provides the set of classes that can be used inside the swing code
javafx.embed.swt Provides the set of classes that can be used inside the swt code
javafx.event Provides the classes that deal with events and their handling
javafx.fxml Contains the set of classes that are responsible of loading hierarchy from
mark-up
javafx.geometry Provides the 2D classes that contains the methods to operate 2D geometry on
the object.
javafx.scene Provides the classes to deal with scene graph API
javafx.scene.canvas Provides the set of classes that deal with canvas.
javafx.scene.control Contains the classes for all JavaFX components.
javafx.scene.effect Contains the set of classes that apply the graphic effects to scene graph nodes
javafx.scene.image Provides the set of classes for loading and displaying images
javafx.scene.input Provides the set of classes for the mouse and keyboard events
javafx.scene.layout Provides the set of classes to support user interface layout
javafx.scene.media Provides the set of classes to integrate audio and video into JavaFX
application
javafx.scene.paint Provides the set of classes for colours and gradients to fill shapes and
backgrounds when rendering scene graph.
javafx.scene.shape Provides the set of 2D classes that performs the operations on objects related
to 2D geometry.
javafx.scene.text Provides the set of classes for fonts and rendering text nodes.
javafx.scene.transform Provides the set of classes that are used to perform rotating, scaling, shearing
operations on objects.
javafx.scene.web Provides means for loading and displaying web content.
javafx.stage Provides the top level container classes for JavaFX content.
javafx.util Provides utilities classes
javafx.util.converter This package is for standard string converters for JavaFX

Scene Graph

It is the starting point of constructing a JavaFX application. It is a hierarchical tree of nodes that represent
all the visual elements of user interface. It also have the capability of handling event. In general, scene
graph can be defined as a collection of nodes.
Each node has its separate id, style and volume. Every node of a scene graph can only have single parent
and zero or more children. All the implementation on a scene graph are actually applied to its node. There
are various classes present in javafx.scene package that are used for creating, modifying and applying
some transformations on the node. We will discuss Scene graph later in detail.

Graphics Engine

The JavaFX graphics engine provides the graphics support to the the scene graph. It basically supports 2D
as well as 3D graphics both. It provides the software rendering when the graphics hardware present on the
system is not able to support hardware accelerated rendering.

The two graphics accelerated pipelines in the JavaFX are:

Prism

prism can be seen as High Performance hardware-accelerated graphics pipeline. It has the capability
to render both 2D and 3D graphics. Prism implements different ways to render graphics on different
platforms.

o DirectX 9 on windows XP or vista


o DirectX 11 on windows 7
o OpenGL on Mac, Linux and embedded
o Java 2D when hardware acceleration is not possible

Quantum Tool kit

Quantum Tool Kit is used to bind prism and glass windowing tool kit together and makes them available
for the above layers in stack.

Glass Windowing tool kit

It is present on the lowest level of JavaFX graphics stack. It basically can be seen as a platform dependent
layer which works as an interface between JavaFX platform and native operating system.

It is responsible for providing the operating system services such as managing the windows, timers, event
queues and surfaces.

Web View

We can also embed the HTML content to a JavaFX scene graph. For this purpose, JavaFX uses a component
called web view. Web view uses web kit which is an internal open source browser and can render HTM5,
DOM, CSS, SVG and JavaScript.

Using web view, we can render the HTML content from JavaFX application , and also apply some CSS styles
to the user interface.
Media Engine

By using Media engine, the JavaFX application can support the playback of audio and video media files.
JavaFX media engine depends upon an open source engine called as G Streamer. The
package javafx.scene.media contains all the classes and interfaces that can provide media functionalities to
JavaFX applications.

JavaFX Application Structure


In general, a JavaFX application will have three major components namely Stage, Scene and Nodes as
shown in the following diagram.

Stage
A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage class of the
package javafx.stage. The primary stage is created by the platform itself. The created stage object is
passed as an argument to the start()method of the Application class (explained in the next section).
A stage has two parameters determining its position namely Width and Height. It is divided as Content
Area and Decorations (Title Bar and Borders).
There are five types of stages available −

• Decorated
• Undecorated
• Transparent
• Unified
• Utility
You have to call the show() method to display the contents of a stage.
Scene
A scene represents the physical contents of a JavaFX application. It contains all the contents of a scene
graph. The class Scene of the package javafx.scene represents the scene object. At an instance, the scene
object is added to only one stage.
You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by passing its
dimensions (height and width) along with the root node to its constructor.
Scene Graph and Nodes
A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast,
a node is a visual/graphical object of a scene graph.
A node may include −
• Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
• UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
• Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
• Media elements such as Audio, Video and Image Objects.
The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all
the nodes.
As discussed earlier a node is of three types −
• Root Node − The first Scene Graph is known as the Root node.
• Branch Node/Parent Node − The node with child nodes are known as branch/parent
nodes. The abstract class named Parent of the package javafx.scene is the base class of all
the parent nodes, and those parent nodes will be of the following types −
o Group − A group node is a collective node that contains a list of children nodes.
Whenever the group node is rendered, all its child nodes are rendered in order.
Any transformation, effect state applied on the group will be applied to all the
child nodes.
o Region − It is the base class of all the JavaFX Node based UI Controls, such as
Chart, Pane and Control.
o WebView − This node manages the web engine and displays its contents.
• Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle,
Ellipse, Box, ImageView, MediaView are examples of leaf nodes.
It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be
clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene.

Creating a JavaFX Application


To create a JavaFX application, you need to instantiate the Application class and implement its abstract
method start(). In this method, we will write the code for the JavaFX Application.

Application Class
The Application class of the package javafx.application is the entry point of the application in JavaFX. To
create a JavaFX application, you need to inherit this class and implement its abstract method start(). In
this method, you need to write the entire code for the JavaFX graphics
In the main method, you have to launch the application using the launch() method. This method internally
calls the start() method of the Application class as shown in the following program.

public class JavafxSample extends Application {


@Override
public void start(Stage primaryStage) throws Exception {
/*
Code for JavaFX application.
(Stage, scene, scene graph)
*/
}
public static void main(String args[]){
launch(args);
}
}
Within the start() method, in order to create a typical JavaFX application, you need to follow the steps
given below −
• Prepare a scene graph with the required nodes.
• Prepare a Scene with the required dimensions and add the scene graph (root node of the
scene graph) to it.
• Prepare a stage and add the scene to the stage and display the contents of the stage.

Preparing the Scene Graph


As per your application, you need to prepare a scene graph with required nodes. Since the root node is the
first node, you need to create a root node. As a root node, you can choose from the Group, Region or
WebView.

Group − A Group node is represented by the class named Group which belongs to the
package javafx.scene, you can create a Group node by instantiating this class as shown below.
Group root = new Group();
The getChildren() method of the Group class gives you an object of the ObservableList class which holds
the nodes. We can retrieve this object and add nodes to it as shown below.
//Retrieving the observable list object
ObservableList list = root.getChildren();

//Setting the text object as a node


list.add(NodeObject);

We can also add Node objects to the group, just by passing them to the Group class and to its constructor
at the time of instantiation, as shown below.
Group root = new Group(NodeObject);

Region − It is the Base class of all the JavaFX Node-based UI Controls, such as −
• Chart − This class is the base class of all the charts and it belongs to the
package javafx.scene.chart.
This class has two sub classes, which are − PieChart and XYChart. These two in turn have
subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of
XY-Plane Charts in JavaFX.
You can use these classes to embed charts in your application.
• Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane,
DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout.
You can use these classes to insert predefined layouts in your application.
• Control − It is the base class of the User Interface controls such as Accordion, ButtonBar,
ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package
javafx.scene.control.
You can use these classes to insert various UI elements in your application.

In a Group, you can instantiate any of the above-mentioned classes and use them as root nodes, as shown
in the following program.
//Creating a Stack Pane
StackPane pane = new StackPane();

//Adding text area to the pane


ObservableList list = pane.getChildren();
list.add(NodeObject);

WebView − This node manages the web engine and displays its contents.
Following is a diagram representing the node class hierarchy of JavaFX.
Preparing the Scene
A JavaFX scene is represented by the Scene class of the package javafx.scene. You can create a Scene by
instantiating this class as shown in the following cod block.
While instantiating, it is mandatory to pass the root object to the constructor of the scene class.
Scene scene = new Scene(root);
You can also pass two parameters of double type representing the height and width of the scene as shown
below.
Scene scene = new Scene(root, 600, 300);

Preparing the Stage


This is the container of any JavaFX application and it provides a window for the application. It is
represented by the Stage class of the package javafx.stage. An object of this class is passed as a parameter
of the start() method of the Applicationclass.
Using this object, you can perform various operations on the stage. Primarily you can perform the
following −
• Set the title for the stage using the method setTitle().
• Attach the scene object to the stage using the setScene() method.
• Display the contents of the scene using the show() method as shown below.

//Setting the title to Stage.


primaryStage.setTitle("Sample application");

//Setting the scene to Stage


primaryStage.setScene(scene);

//Displaying the stage


primaryStage.show();

Lifecycle of JavaFX Application


The JavaFX Application class has three life cycle methods, which are −
• start() − The entry point method where the JavaFX graphics code is to be written.
• stop() − An empty method which can be overridden, here you can write the logic to stop the
application.
• init() − An empty method which can be overridden, but you cannot create stage or scene in
this method.
In addition to these, it provides a static method named launch() to launch JavaFX application.
Since the launch() method is static, you need to call it from a static context (main generally). Whenever a
JavaFX application is launched, the following actions will be carried out (in the same order).
• An instance of the application class is created.
• Init() method is called.
• The start() method is called.
• The launcher waits for the application to finish and calls the stop() method.

Terminating the JavaFX Application


When the last window of the application is closed, the JavaFX application is terminated implicitly. You can
turn this behavior off by passing the Boolean value “False” to the static method setImplicitExit() (should
be called from a static context).
You can terminate a JavaFX application explicitly using the methods Platform.exit()or System.exit(int).

Example 1 – Creating an Empty Window


This section teaches you how to create a JavaFX sample application which displays an empty window.
Following are the steps −

Step 1: Creating a Class


Create a Java class and inherit the Application class of the package javafx.application and implement the
start() method of this class as follows.
public class JavafxSample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}

Step 2: Creating a Group Object


In the start() method creates a group object by instantiating the class named Group, which belongs to the
package javafx.scene, as follows.
Group root = new Group();
Step 3: Creating a Scene Object
Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this
class, pass the Group object (root), created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of
the screen along with the object of the Group class as follows.
Scene scene = new Scene(root,600, 300);

Step 4: Setting the Title of the Stage


You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a
Stage object which is passed to the start method of the scene class, as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as shown below.
primaryStage.setTitle("Sample Application");

Step 5: Adding Scene to the Stage


You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the
Scene object prepared in the previous steps using this method as shown below.
primaryStage.setScene(scene);

Step 6: Displaying the Contents of the Stage


Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();

Step 7: Launching the Application


Launch the JavaFX application by calling the static method launch() of the Application class from the
main method as follows.
public static void main(String args[]){
launch(args);
}

Example
The following program generates an empty JavaFX window. Save this code in a file with the
name JavafxSample.java
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class JavafxSample extends Application {


@Override
public void start(Stage primaryStage) throws Exception {
//creating a Group object
Group group = new Group();

//Creating a Scene by passing the group object, height and width


Scene scene = new Scene(group ,600, 300);

//setting color to the scene


scene.setFill(Color.BROWN);

//Setting the title to Stage.


primaryStage.setTitle("Sample Application");

//Adding the scene to Stage


primaryStage.setScene(scene);

//Displaying the contents of the stage


primaryStage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac JavafxSample.java
java JavafxSample
On executing, the above program generates a JavaFX window as shown below.
Example 2 – Displaying Text
We can also embed text in JavaFX scene. This example shows how to embed text in JavaFX.
Following are the steps –

Step 1: Creating a Class


Create a Java Class and inherit the Application class of the package javafx.application and implement
the start() method of this class as follows.
public class DrawingLine extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}

Step 2: Embedding Text


You can embed text into a JavaFX scene by instantiating the class named Text which belongs to a
package javafx.scene.shape, instantiate this class.
You can instantiate this class by passing text to be embedded, in String format Or, you can create text
object using the default constructor as shown below.
//Creating a Text object
Text text = new Text();

Step 3: Setting the Font


You can set font to the text using the setFont() method of the Text class. This method accepts a font object
as parameters. Set the font of the given text to 45 as shown below.
//Setting font to the text
text.setFont(new Font(45));

Step 4: Setting the Position of the Text


You can set the position of the text on the X-Y plane by setting the X,Y coordinates using the respective
setter methods setX() and setY() as follows.
//setting the position of the text
text.setX(50);
text.setY(150);

Step 5: Setting the text to be added


You can set the text to be added using the setText() method of the Text class. This method accepts a string
parameter representing the text to be added.
text.setText("Welcome to RIT");
Step 6: Creating a Group Object
In the start() method, create a group object by instantiating the class named Group, which belongs to the
package javafx.scene.
Pass the Text (node) object, created in the previous step, as a parameter to the constructor of the Group
class, in order to add it to the group as follows −
Group root = new Group(text)

Step 7: Creating a Scene Object


Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this
class, pass the Group object (root), created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of
the screen along with the object of the Group class as follows.
Scene scene = new Scene(group ,600, 300);

Step 8: Setting the Title of the Stage


You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a
Stage object which is passed to the start method of the scene class, as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as shown below.
primaryStage.setTitle("Sample Application");

Step 9: Adding Scene to the Stage


You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the
Scene object prepared in the previous steps using this method as follows.
primaryStage.setScene(scene);

Step 10: Displaying the Contents of the Stage


Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();

Step 11: Launching the Application


Launch the JavaFX application by calling the static method launch() of the Application class from the
main method as follows.
public static void main(String args[]){
launch(args);
}

Example
Following is the program to display text using JavaFX. Save this code in a file with
name DisplayingText.java.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.Text;

public class DisplayingText extends Application {


@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();

//Setting font to the text


text.setFont(new Font(45));

//setting the position of the text


text.setX(50);
text.setY(150);

//Setting the text to be added.


text.setText("Welcome to RIT");

//Creating a Group object


Group root = new Group();

//Retrieving the observable list object


ObservableList list = root.getChildren();

//Setting the text object as a node to the group object


list.add(text);

//Creating a scene object


Scene scene = new Scene(root, 600, 300);

//Setting title to the Stage


stage.setTitle("Sample Application");

//Adding scene to the stage


stage.setScene(scene);

//Displaying the contents of the stage


stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac DisplayingText.java
java DisplayingText

1.2 Event Basics

In JavaFX, we can develop GUI applications, web applications and graphical applications. In such
applications, whenever a user interacts with the application (nodes), an event is said to have been
occurred.
For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an
item from list, scrolling the page are the activities that causes an event to happen.

Types of Events
The events can be broadly classified into the following two categories −
• Foreground Events − Those events which require the direct interaction of a user. They are
generated as consequences of a person interacting with the graphical components in a
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page, etc.

• Background Events − Those events that don't require the interaction of end-user are known
as background events. The operating system interruptions, hardware or software failure,
timer expiry, operation completion is the example of background events.

Events in JavaFX
JavaFX provides support to handle a wide variety of events. The class named Event of the
package javafx.event is the base class for an event.
An instance of any of its subclass is an event. JavaFX provides a wide variety of events. Some of them are
listed below.
• Mouse Event − This is an input event that occurs when a mouse is clicked. It is represented
by the class named MouseEvent. It includes actions like mouse clicked, mouse pressed,
mouse released, mouse moved, mouse entered target, mouse exited target, etc.
• Key Event − This is an input event that indicates the key stroke occurred on a node. It is
represented by the class named KeyEvent. This event includes actions like key pressed, key
released and key typed.
• Drag Event − This is an input event which occurs when the mouse is dragged. It is
represented by the class named DragEvent. It includes actions like drag entered, drag
dropped, drag entered target, drag exited target, drag over, etc.
• Window Event − This is an event related to window showing/hiding actions. It is
represented by the class named WindowEvent. It includes actions like window hiding,
window shown, window hidden, window showing, etc.

Event Handling
Event Handling is the mechanism that controls the event and decides what should happen, if an event
occurs. This mechanism has the code which is known as an event handler that is executed when an event
occurs.
JavaFX provides handlers and filters to handle events. In JavaFX every event has −
• Target − The node on which an event occurred. A target can be a window, scene, and a node.

• Source − The source from which the event is generated will be the source of the event. In the
above scenario, mouse is the source of the event.

• Type − Type of the occurred event; in case of mouse event – mouse pressed; mouse released
are the type of events.

Assume that we have an application which has a Circle, Stop and Play Buttons inserted using a group
object as follows −

If you click on the play button, the source will be the mouse, the target node will be the play button and the
type of the event generated is the mouse click.

Phases of Event Handling in JavaFX

Whenever an event is generated, JavaFX undergoes the following phases.


Route Construction
Whenever an event is generated, the default/initial route of the event is determined by construction of
an Event Dispatch chain. It is the path from the stage to the source Node.
Following is the event dispatch chain for the event generated, when we click on the play button in the
above scenario.

Event Capturing Phase


After the construction of the event dispatch chain, the root node of the application dispatches the event.
This event travels to all nodes in the dispatch chain (from top to bottom). If any of these nodes has
a filter registered for the generated event, it will be executed. If none of the nodes in the dispatch chain has
a filter for the event generated, then it is passed to the target node and finally the target node processes the
event.
Event Bubbling Phase
In the event bubbling phase, the event is travelled from the target node to the stage node (bottom to top).
If any of the nodes in the event dispatch chain has a handlerregistered for the generated event, it will be
executed. If none of these nodes have handlers to handle the event, then the event reaches the root node
and finally the process will be completed.
Event Handlers and Filters
Event filters and handlers are those which contains application logic to process an event. A node can
register to more than one handler/filter. In case of parent–child nodes, you can provide a common
filter/handler to the parents, which is processed as default for all the child nodes.
As mentioned above, during the event, processing is a filter that is executed and during the event bubbling
phase, a handler is executed. All the handlers and filters implement the interface EventHandler of the
package javafx.event.

Adding and Removing Event Filter

To add an event filter to a node, you need to register this filter using the method addEventFilter() of
the Node class.
//Creating the mouse event handler
EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Adding event Filter
Circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
In the same way, you can remove a filter using the method removeEventFilter() as shown below −
circle.removeEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);

Event Handling Example

Following is an example demonstrating the event handling in JavaFX using the event filters. Save this code
in a file with name EventFiltersExample.java.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;

import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class EventFiltersExample extends Application {


@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);

//Setting the radius of the circle


circle.setRadius(25.0f);

//Setting the color of the circle


circle.setFill(Color.BROWN);

//Setting the stroke width of the circle


circle.setStrokeWidth(20);

//Setting the text


Text text = new Text("Click on the circle to change its color");

//Setting the font of the text


text.setFont(Font.font(null, FontWeight.BOLD, 15));

//Setting the color of the text


text.setFill(Color.CRIMSON);

//setting the position of the text


text.setX(150);
text.setY(50);

//Creating the mouse event handler


EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Registering the event filter
circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);

//Creating a Group object


Group root = new Group(circle, text);

//Creating a scene object


Scene scene = new Scene(root, 600, 300);

//Setting the fill color to the scene


scene.setFill(Color.LAVENDER);

//Setting title to the Stage


stage.setTitle("Event Filters Example");
//Adding scene to the stage
stage.setScene(scene);

//Displaying the contents of the stage


stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac EventFiltersExample.java
java EventFiltersExample
On executing, the above program generates a JavaFX window as shown below.

Adding and Removing Event Handlers

To add an event handler to a node, you need to register this handler using the
method addEventHandler() of the Node class as shown below.
//Creating the mouse event handler
EventHandler<javafx.scene.input.MouseEvent> eventHandler =
new EventHandler<javafx.scene.input.MouseEvent>() {

@Override
public void handle(javafx.scene.input.MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Adding the event handler
circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler);
In the same way, you can remove an event handler using the method removeEventHandler() as shown
below −
circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);
Example
The following program is an example demonstrating the event handling in JavaFX using the event
handlers.
Save this code in a file with name EventHandlersExample.java.
import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;

import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;

import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;

public class EventHandlersExample extends Application {

@Override
public void start(Stage stage) {
//Drawing a Box
Box box = new Box();

//Setting the properties of the Box


box.setWidth(150.0);
box.setHeight(150.0);
box.setDepth(100.0);
//Setting the position of the box
box.setTranslateX(350);
box.setTranslateY(150);
box.setTranslateZ(50);

//Setting the text


Text text = new Text("Type any letter to rotate the box,
and click on the box to stop the rotation");

//Setting the font of the text


text.setFont(Font.font(null, FontWeight.BOLD, 15));

//Setting the color of the text


text.setFill(Color.CRIMSON);

//setting the position of the text


text.setX(20);
text.setY(50);

//Setting the material of the box


PhongMaterial material = new PhongMaterial();
material.setDiffuseColor(Color.DARKSLATEBLUE);

//Setting the diffuse color material to box


box.setMaterial(material);

//Setting the rotation animation to the box


RotateTransition rotateTransition = new RotateTransition();

//Setting the duration for the transition


rotateTransition.setDuration(Duration.millis(1000));

//Setting the node for the transition


rotateTransition.setNode(box);

//Setting the axis of the rotation


rotateTransition.setAxis(Rotate.Y_AXIS);

//Setting the angle of the rotation


rotateTransition.setByAngle(360);

//Setting the cycle count for the transition


rotateTransition.setCycleCount(50);

//Setting auto reverse value to false


rotateTransition.setAutoReverse(false);

//Creating a text filed


TextField textField = new TextField();
//Setting the position of the text field
textField.setLayoutX(50);
textField.setLayoutY(100);

//Handling the key typed event


EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
//Playing the animation
rotateTransition.play();
}
};
//Adding an event handler to the text feld
textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);

//Handling the mouse clicked event(on box)


EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =
new EventHandler<javafx.scene.input.MouseEvent>() {

@Override
public void handle(javafx.scene.input.MouseEvent e) {
rotateTransition.stop();
}
};
//Adding the event handler to the box
box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox);

//Creating a Group object


Group root = new Group(box, textField, text);

//Creating a scene object


Scene scene = new Scene(root, 600, 300);

//Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);

//Setting title to the Stage


stage.setTitle("Event Handlers Example");

//Adding scene to the stage


stage.setScene(scene);

//Displaying the contents of the stage


stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac EventHandlersExample.java
java EventHandlersExample
On executing, the above program generates a JavaFX window displaying a text field and a 3D box as shown
below −

Here, if you type a letter in the text field, the 3D box starts rotating along the x axis. If you click on the box
again the rotation stops.

Convenience Methods
This topic describes convenience methods that you can use to register event handlers within your JavaFX
application. Learn an easy way to create and register event handlers to respond to mouse events, keyboard
events, action events, drag-and-drop events, window events, and others.

Some JavaFX classes define event handler properties, which provide a way to register event handlers.
Setting an event handler property to a user-defined event handler automatically registers the handler to
receive the corresponding event type. The setter methods for the event handler properties are
convenience methods for registering event handlers.
Using Convenience Methods
Many of the convenience methods are defined in the Node class and are available to all of its subclasses.
Other classes also contain convenience methods. The following table describes the events that convenience
methods can be used to handle and identifies the classes in which the convenience methods are defined.

Table - Classes with Convenience Methods for Event Handling

User Action Event Type Class

Key on the keyboard is pressed. KeyEvent Node, Scene

Mouse is moved or a button on the mouse MouseEvent Node, Scene


is pressed.

Full mouse press-drag-release action is MouseDragEvent Node, Scene


performed.

Input from an alternate method for InputMethodEvent Node, Scene


entering characters (typically for a foreign
language) is generated, changed, removed,
or committed.

Platform-supported drag and drop action DragEvent Node, Scene


is performed.

Object is scrolled. ScrollEvent Node, Scene

Rotation gesture is performed on an object RotateEvent Node, Scene

Swipe gesture is performed on an object SwipeEvent Node, Scene

An object is touched TouchEvent Node, Scene

Zoom gesture is performed on an object ZoomEvent Node, Scene

Context menu is requested ContextMenuEvent Node, Scene

Button is pressed, combo box is shown or ActionEvent ButtonBase, ComboBoxBase, ContextM


hidden, or a menu item is selected. enu, MenuItem, TextField
User Action Event Type Class

Item in a list, table, or tree is edited. • ListView.Edit • ListView


Event • TableColumn
• TableColumn. • TreeView
CellEditEvent
• TreeView.Edit
Event

Media player encounters an error. MediaErrorEvent MediaView

Menu is either shown or hidden. Event Menu

Popup window is hidden. Event PopupWindow

Tab is selected or closed. Event Tab

Window is closed, shown, or hidden. WindowEvent Window

Convenience methods for registering event handlers have the following format:

setOnEvent-type(EventHandler<? super event-class> value)

Event-type is the type of event that the handler processes, for


example, setOnKeyTyped for KEY_TYPED events or setOnMouseClicked for MOUSE_CLICKED events. event-
class is the class that defines the event type, for example, KeyEvent for events related to keyboard input
or MouseEventfor events related to mouse input. The string <? super event-class> indicates that the
method accepts an event handler for event-class or an event handler for one of its super classes as the
argument. For example, an event handler for InputEvent could be used when the event is either a keyboard
event or a mouse event.

The following statement shows the definition for the method that registers an event handler to handle the
events that are generated when a key is typed, that is, when a key is pressed and released:

setOnKeyTyped(EventHandler<? super KeyEvent> value)


You can create and register your event handler in a single step by defining the handler as an anonymous
class in the call to the convenience method. The event handler must implement the handle() method to
provide the code needed to process the event.

A example of the use of a convenience method is shown in the code that is generated when you use the
NetBeans IDE to create a JavaFX application. If you select the Create Application Class option when you
create your JavaFX application, the main class that is created contains a "Hello World" application. The
generated code is shown in Example 2-1.

Example 1 Hello World Example

package yourapplication;

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.stage.Stage;

public class YourApplication extends Application {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
Button btn = new Button();
btn.setLayoutX(100);
btn.setLayoutY(80);
btn.setText("Hello World");
btn.setOnAction(new EventHandler<ActionEvent>() {

public void handle(ActionEvent event) {


System.out.println("Hello World");
}
});
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.show();
}
}
The "Hello World" code creates a window with a single button. The setOnAction() method is used to
register an event handler that handles the action events that are dispatched when the button is clicked.
The handle() method in the event handler handles the event by printing the string "Hello World" to the
console.

Examples for Mouse Events

Convenience methods for registering event handlers for mouse events


include setOnMouseEntered, setOnMouseExited, and setOnMousePressed.

Example 2 Sample Event Handlers for Mouse Events

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class Mouse extends Application{

public void start(Stage primaryStage) {

primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 500, 500);

final Circle circle = new Circle(100,100,50, Color.RED);

circle.setOnMouseEntered(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse entered");
}
});

circle.setOnMouseExited(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse exited");
}
});

circle.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse pressed");
}
});

root.getChildren().add(circle);
primaryStage.setScene(scene);
primaryStage.show();

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

Examples for Keyboard Events


Convenience methods for registering event handlers for keyboard events
include setOnKeyPressedand setOnKeyReleased.
Example 3 Sample Event Handlers for Keyboard Events

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;

public class helloworld extends Application{

public void start(Stage primaryStage) {

primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 500, 500);

final TextField textBox = new TextField();


textBox.setPromptText("Write here");

textBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
System.out.println("Key Pressed: " + ke.getText());
}
});

textBox.setOnKeyReleased(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
System.out.println("Key Released: " + ke.getText());
}
});

root.getChildren().add(textBox);
primaryStage.setScene(scene);
primaryStage.show();

}
public static void main(String[] args) {
// TODO Auto-generated method stub
Application.launch(args);
}

}
2. Controls

JavaFX UI Controls

This part of the tutorial provides you the in-depth knowledge of JavaFX UI controls. The graphical user
interface of every desktop application mainly considers UI elements, layouts and behaviour.

The UI elements are the one which are actually shown to the user for interaction or information exchange.
Layout defines the organization of the UI elements on the screen. Behaviour is the reaction of the UI
element when some event is occurred on it.

However, the package javafx.scene.control provides all the necessary classes for the UI components like
Button, Label, etc. Every class represents a specific UI control and defines some methods for their styling.

SN Control Description
1 Label Label is a component that is used to define a simple text on the screen.
Typically, a label is placed with the node, it describes.
2 Button Button is a component that controls the function of the application.
Button class is used to create a labelled button.
3 RadioButton The Radio Button is used to provide various options to the user. The user
can only choose one option among all. A radio button is either selected or
deselected.
4 CheckBox Check Box is used to get the kind of information from the user which
contains various choices. User marked the checkbox either on (true) or
off(false).
5 TextField Text Field is basically used to get the input from the user in the form of
text. javafx.scene.control.TextField represents TextField
6 PasswordField PasswordField is used to get the user's password. Whatever is typed in
the passwordfield is not shown on the screen to anyone.
7 HyperLink HyperLink are used to refer any of the webpage through your appication.
It is represented by the class javafx.scene.control.HyperLink
8 Slider Slider is used to provide a pane of options to the user in a graphical form
where the user needs to move a slider over the range of values to select
one of them.
9 ProgressBar Progress Bar is used to show the work progress to the user. It is
represented by the class javafx.scene.control.ProgressBar.
10 ProgressIndicator Instead of showing the analogue progress to the user, it shows the digital
progress so that the user may know the amount of work done in
percentage.
11 ScrollBar JavaFX Scroll Bar is used to provide a scroll bar to the user so that the
user can scroll down the application pages.
12 Menu JavaFX provides a Menu class to implement menus. Menu is the main
component of any application.
13 ToolTip JavaFX ToolTip is used to provide hint to the user about any component.
It is mainly used to provide hints about the text fields or password fields
being used in the application.

2.1 Checkbox

The Check Box is used to provide more than one choices to the user. It can be used in a scenario where the
user is prompted to select more than one option or the user wants to select multiple options. It is different
from the radiobutton in the sense that, we can select more than one checkboxes in a scenerio.

Instantiate javafx.scene.control.CheckBox class to implement CheckBox.

Use the following line in the code to create a blank CheckBox.

1. CheckBox checkbox = new CheckBox();

Use the following line to attach a label with the checkbox.

1. CheckBox checkbox = new CheckBox("Label Name");

We can change the CheckBox Label at any time by calling an instance method setText("text"). We can
make it selected by calling setSelected("true")

The following code implements CheckBox into our application.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class CheckBoxTest extends Application {

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label l = new Label("What do you listen: ");
CheckBox c1 = new CheckBox("Radio one");
CheckBox c2 = new CheckBox("Radio Mirchi");
CheckBox c3 = new CheckBox("Red FM");
CheckBox c4 = new CheckBox("FM GOLD");
HBox root = new HBox();
root.getChildren().addAll(l,c1,c2,c3,c4);
root.setSpacing(5);
Scene scene=new Scene(root,800,200);
primaryStage.setScene(scene);
primaryStage.setTitle("CheckBox Example");
primaryStage.show();
}
}

Output:
2.2 ToggleButton

A JavaFX ToggleButton is a button that can be selected or not selected. Like a button that stays in when you
press it, and when you press it the next time it comes out again. Toggled - not toggled. The JavaFX
ToggleButton is represented by the class javafx.scene.control.ToggleButton .

Creating a ToggleButton

You create a JavaFX ToggleButton by creating an instance of the ToggleButton class. Here is an example of
creating a JavaFX ToggleButton instance:

ToggleButton toggleButton1 = new ToggleButton("Left");

This example creates a ToggleButton with the text Left on.

Adding a ToggleButton to the Scene Graph

To make a ToggleButton visible you must add it to the JavaFX scene graph. This means adding it to a Scene,
or as child of a layout which is attached to a Scene object.

Here is an example that attaches a JavaFX ToggleButton to the scene graph:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ToggleButtonExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");

ToggleButton toggleButton1 = new ToggleButton("Left");

HBox hbox = new HBox(toggleButton1);

Scene scene = new Scene(hbox, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


Application.launch(args);
}
}

The application resulting from running the above example code is illustrated in the following two
screenshots. The first screenshot shows a ToggleButton which is not pressed, and the second screenshot
shows the same ToggleButton pressed (selected, activated etc.):

ToggleButton Text

You can set or change the text of a JavaFX ToggleButton via its setText() method. Here is an example of
changing the text of a JavaFX ToggleButton via setText():

ToggleButton toggleButton = new ToggleButton("Toggle This!");

toggleButton.setText("New Text");
ToggleButton Font

You can set the font to use to render the button text of a JavaFX ToggleButton via its setFont() method. You
can read more about creating fonts in my JavaFX Fonts tutorial. Here is an example of setting the font of a
JavaFX ToggleButton:

ToggleButton toggleButton = new ToggleButton("Toggle This!");

Font arialFontBold36 = Font.font("Arial", FontWeight.BOLD, 36);

toggleButton.setFont(arialFontBold36);
Reading Selected State

The ToggleButton class has a method named isSelected which lets you determine if theToggleButton is
selected (pressed) or not. The isSelected() method returns a booleanwith the value true if
the ToggleButton is selected, and false if not. Here is an example:
boolean isSelected = toggleButton1.isSelected();
ToggleGroup

You can group JavaFX ToggleButton instances into a ToggleGroup. A ToggleGroup allows at most
one ToggleButton to be toggled (pressed) at any time. The ToggleButton instances in a ToggleGroup thus
functions similarly to radio buttons.

Here is a JavaFX ToggleGroup example:

ToggleButton toggleButton1 = new ToggleButton("Left");


ToggleButton toggleButton2 = new ToggleButton("Right");
ToggleButton toggleButton3 = new ToggleButton("Up");
ToggleButton toggleButton4 = new ToggleButton("Down");

ToggleGroup toggleGroup = new ToggleGroup();

toggleButton1.setToggleGroup(toggleGroup);
toggleButton2.setToggleGroup(toggleGroup);
toggleButton3.setToggleGroup(toggleGroup);
toggleButton4.setToggleGroup(toggleGroup);

Here is a full example that adds the 4 ToggleButton instances to a ToggleGroup, and adds them to the scene
graph too:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ToggleButtonExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");

ToggleButton toggleButton1 = new ToggleButton("Left");


ToggleButton toggleButton2 = new ToggleButton("Right");
ToggleButton toggleButton3 = new ToggleButton("Up");
ToggleButton toggleButton4 = new ToggleButton("Down");
ToggleGroup toggleGroup = new ToggleGroup();

toggleButton1.setToggleGroup(toggleGroup);
toggleButton2.setToggleGroup(toggleGroup);
toggleButton3.setToggleGroup(toggleGroup);
toggleButton4.setToggleGroup(toggleGroup);

HBox hbox = new HBox(toggleButton1, toggleButton2, toggleButton3, toggleButton4);

Scene scene = new Scene(hbox, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();

public static void main(String[] args) {


Application.launch(args);
}
}

The resulting applications looks like this:

Reading Selected State of a ToggleGroup

You can read which ToggleButton of a ToggleGroup is selected (pressed) using


thegetSelectedToggle() method, like this:

ToggleButton selectedToggleButton =
(ToggleButton) toggleGroup.getSelectedToggle();

If no ToggleButton is selected the getSelectedToggle() method returns null .


2.3 RadioButtons

A JavaFX RadioButton is a button that can be selected or not selected. The RadioButton is very similar to
the JavaFX ToggleButton, but with the difference that a RadioButtoncannot be "unselected" once selected.
If RadioButtons are part of a ToggleGroup then once a RadioButton has been selected for the first time,
there must be one RadioButton selected in the ToggleGroup .

The JavaFX RadioButton is represented by the class javafx.scene.control.RadioButton.


The RadioButton class is a subclass of the ToggleButton class.

Creating a RadioButton

You create a JavaFX RadioButton using its constructor. Here is a JavaFX RadioButtoninstantiation example:

RadioButton radioButton1 = new RadioButton("Left");

The String passed as parameter to the RadioButton constructor is displayed next to theRadioButton.

Adding a RadioButton to the Scene Graph

To make a RadioButton visible you must add it to the scene graph of your JavaFX application. This means
adding the RadioButton to a Scene, or as child of a layout which is attached to a Scene object.

Here is an example that attaches a JavaFX RadioButton to the scene graph:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class RadioButtonExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");

RadioButton radioButton1 = new RadioButton("Left");

HBox hbox = new HBox(radioButton1);

Scene scene = new Scene(hbox, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();

public static void main(String[] args) {


Application.launch(args);
}

The application resulting from running this example looks like this:

Reading Selected State

The RadioButton class has a method named isSelected which lets you determine if theRadioButton is
selected or not. The isSelected() method returns a boolean with the value true if the RadioButton is
selected, and false if not. Here is an example:

boolean isSelected = radioButton1.isSelected();


ToggleGroup

You can group JavaFX RadioButton instances into a ToggleGroup. A ToggleGroup allows at most
one RadioButton to be selected at any time.

Here is a JavaFX ToggleGroup example:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class RadioButtonExperiments extends Application {


@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");

RadioButton radioButton1 = new RadioButton("Left");


RadioButton radioButton2 = new RadioButton("Right");
RadioButton radioButton3 = new RadioButton("Up");
RadioButton radioButton4 = new RadioButton("Down");

ToggleGroup radioGroup = new ToggleGroup();

radioButton1.setToggleGroup(radioGroup);
radioButton2.setToggleGroup(radioGroup);
radioButton3.setToggleGroup(radioGroup);
radioButton4.setToggleGroup(radioGroup);

HBox hbox = new HBox(radioButton1, radioButton2, radioButton3, radioButton4);

Scene scene = new Scene(hbox, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();

public static void main(String[] args) {


Application.launch(args);
}

The application resulting from running this example looks like this:

Reading Selected State of a ToggleGroup

You can read which RadioButton of a ToggleGroup is selected using thegetSelectedToggle() method, like
this:
RadioButton selectedRadioButton =
(RadioButton) toggleGroup.getSelectedToggle();

If no RadioButton is selected the getSelectedToggle() method returns null .

2.4 ListView

The JavaFX ListView control enables users to choose one or more options from a predefined list of choices.
The JavaFX ListView control is represented by the class javafx.scene.control.ListView . This JavaFX
ListView tutorial will explain how to use the ListView class.

Creating a ListView

You create a ListView simply by creating a new instance of the ListView class. Here is a
JavaFX ListView instantiation example:

ListView listView = new ListView();


Adding Items to a ListView

You can add items (options) to a ListView by obtaining its item collection and add items to it. Here is an
example that adds items to a JavaFX ListView :

listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Adding a ListView to the Scene Graph

To make a ListView visible you must add it to the scene graph. This means that you must add
the ListView to a Scene object or to some layout component which is then attached to the Scene object.

Here is an example showing how to add a JavaFX ListView to the scene graph:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ListViewExperiments extends Application {


@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");

ListView listView = new ListView();

listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");

HBox hbox = new HBox(listView);

Scene scene = new Scene(hbox, 300, 120);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


Application.launch(args);
}
}

The application resulting from running this example would look similar to this screenshot:

Notice how the ListView shows multiple options by default. You can set a height and width for a ListView,
but you cannot set explicitly how many items should be visible. The height determines that based on the
height of each item displayed.

If there are more items in the ListView than can fit into its visiible area, the ListView will add scroll bars so
the user can scroll up and down over the items.

Reading the Selected Value

You can read the selected indexes of a ListView via its SelectionModel. Here is an example showing how to
read the selected indexes of a JavaFX ListView:
ObservableList selectedIndices =
listView.getSelectionModel().getSelectedIndices();

The OberservableList will contain Integer objects representing the indexes of the selected items in
the ListView.

Here is a full JavaFX example with a button added which reads the selected items of the ListView when
clicked:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ListViewExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");

ListView listView = new ListView();

listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");

Button button = new Button("Read Selected Value");

button.setOnAction(event -> {
ObservableList selectedIndices = listView.getSelectionModel().getSelectedIndices();

for(Object o : selectedIndices){
System.out.println("o = " + o + " (" + o.getClass() + ")");
}
});

VBox vBox = new VBox(listView, button);


Scene scene = new Scene(vBox, 300, 120);
primaryStage.setScene(scene);
primaryStage.show();

public static void main(String[] args) {


Application.launch(args);
}
}
Allowing Multiple Items to be Selected

To allow multiple items in the ListView to be selected you need to set the corresponding selection mode on
the ListView selection model. Here is an example of setting the selection mode on the JavaFX ListView:

listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

Once you have set the SelectionMode.MULTIPLE on the ListView selection model, the user can select
multiple items in the ListView by holding down SHIFT or CTRL when selecting additional items after the
first selected item.

Here is a full JavaFX example that shows how to set a ListView into multiple selection mode, including a
button which when clicked will write out the indices of the selected items in the ListView :

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ListViewExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");

ListView listView = new ListView();


listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");

Button button = new Button("Read Selected Value");

button.setOnAction(event -> {
ObservableList selectedIndices = listView.getSelectionModel().getSelectedIndices();

for(Object o : selectedIndices){
System.out.println("o = " + o + " (" + o.getClass() + ")");
}
});

VBox vBox = new VBox(listView, button);

Scene scene = new Scene(vBox, 300, 120);


primaryStage.setScene(scene);
primaryStage.show();

public static void main(String[] args) {


Application.launch(args);
}
}

2.5 ComboBox

The JavaFX ComboBox control enables users to choose an option from a predefined list of choices, or type
in another value if none of the predefined choices matches what the user want to select. The JavaFX
ComboBox control is represented by the class javafx.scene.control.ComboBox . This JavaFX ComboBox
tutorial will explain how to use the ComboBox class.

Creating a ComboBox

You create a ComboBox simply by creating a new instance of the ComboBox class. Here is a
JavaFX ComboBox instantiation example:
ComboBox comboBox = new ComboBox();
Adding Choices to a ComboBox

You can add choices to a ComboBox by obtaining its item collection and add items to it. Here is an example
that adds choices to a JavaFX ComboBox :

comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
Adding a ComboBox to the Scene Graph

To make a ComboBox visible you must add it to the scene graph. This means that you must add
the ComboBox to a Scene object or to some layout component which is then attached to the Scene object.

Here is an example showing how to add a JavaFX ComboBox to the scene graph:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ComboBoxExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ComboBox Experiment 1");

ComboBox comboBox = new ComboBox();

comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");

HBox hbox = new HBox(comboBox);

Scene scene = new Scene(hbox, 200, 120);


primaryStage.setScene(scene);
primaryStage.show();

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

The application resulting from running this example would look similar to this:

Making the ComboBox Editable

A ComboBox is not editable by default. That means, that by default the user cannot enter anything
themselves, but only choose from the predefined list of options. To make a ComboBox editable you must
call the setEditable() method of the ComboBox. Here is an example making a JavaFX ComboBox editable:

comboBox.setEditable(true);

Once the ComboBox is editable the user can type in values into the ComboBox. The entered value is also
read via the getValue() method as explained earlier. The following screenthot shows a
JavaFX ComboBox which is editable, and with a custom value entered:

Reading the Selected Value

You can read the selected value of a ComboBox via its getValue() method. If no choice is selected,
the getValue() method returns null. Here is an example of calling getValue():
String value = (String) comboBox.getValue();
Listening for Selection

It is possible to listen for selection changes in a JavaFX ComboBox by setting an action listener on the
ComboBox via its setOnAction() method. Here is an example of setting an action listener on a ComboBox
which reads what value was selected in the ComboBox:

ComboBox comboBox = new ComboBox();

comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");

comboBox.setOnAction((event) -> {
int selectedIndex = comboBox.getSelectionModel().getSelectedIndex();
Object selectedItem = comboBox.getSelectionModel().getSelectedItem();

System.out.println("Selection made: [" + selectedIndex + "] " + selectedItem);


System.out.println(" ComboBox.getValue(): " + comboBox.getValue());
});

2.6 ChoiceBox

The JavaFX ChoiceBox control enables users to choose an option from a predefined list of choices. The
JavaFX ChoiceBox control is represented by the class javafx.scene.control.ChoiceBox . This JavaFX
ChoiceBox tutorial will explain how to use the ChoiceBox class.

Creating a ChoiceBox

You create a ChoiceBox simply by creating a new instance of the ChoiceBox class. Here is a
JavaFX ChoiceBox instantiation example:

ChoiceBox choiceBox = new ChoiceBox();


Adding Choices to a ChoiceBox

You can add choices to a ChoiceBox by obtaining its item collection and add items to it. Here is an example
that adds choices to a JavaFX ChoiceBox :

choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");
Adding a ChoiceBox to the Scene Graph
To make a ChoiceBox visible you must add it to the scene graph. This means that you must add
the ChoiceBox to a Scene object or to some layout component which is then attached to the Scene object.

Here is an example showing how to add a JavaFX ChoiceBox to the scene graph:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ChoiceBoxExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ChoiceBox Experiment 1");

ChoiceBox choiceBox = new ChoiceBox();

choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");

HBox hbox = new HBox(choiceBox);

Scene scene = new Scene(hbox, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();

public static void main(String[] args) {


Application.launch(args);
}
}

The application resulting from running this example would look similar to this:
Reading the Selected Value

You can read the selected value of a ChoiceBox via its getValue() method. If no choice is selected,
the getValue() method returns null. Here is an example of calling getValue():

String value = (String) choiceBox.getValue();


Listening for Selection

It is possible to listen for selection changes in a JavaFX ChoiceBox by setting an action listener on the
ChoiceBox via its setOnAction() method. Here is an example of setting an action listener on a ChoiceBox
which reads what value was selected in the ChoiceBox:

ChoiceBox choiceBox = new ChoiceBox();

choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");

choiceBox.setOnAction((event) -> {
int selectedIndex = choiceBox.getSelectionModel().getSelectedIndex();
Object selectedItem = choiceBox.getSelectionModel().getSelectedItem();

System.out.println("Selection made: [" + selectedIndex + "] " + selectedItem);


System.out.println(" ChoiceBox.getValue(): " + choiceBox.getValue());
});

2.7 Text Controls

The JavaFX Text control can display a text inside a JavaFX GUI. The JavaFX Text control is represented by
the JavaFX class javafx.scene.text.Text . You can set the font to be used by the Text control, text size, font
decorations and many other things.

Since the JavaFX Text control is a subclass of the JavaFX Shape class, the Text class has all the same
methods available that other JavaFX Shape objects do - e.g. fill and stroke color and style.
The JavaFX Text control is also a subclass of the JavaFX Node class, so the Text class also has all the same
methods available as any other JavaFX Node has, meaning you can set effects on it etc.

JavaFX Text Example

Here is a simple, complete JavaFX text example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class TextExample extends Application {

public static void main(String[] args) {


launch(args);
}

public void start(Stage primaryStage) {

Text text = new Text("This is a JavaFX text.");

Scene scene = new Scene(new VBox(text), 300, 250);


primaryStage.setScene(scene);
primaryStage.show();

}
}
Set Text

You can set the text of a JavaFX Text object via its setText() method. Here is an example of setting the text
of a JavaFX Text control via setText():

Text text = new Text();

text.setText("This is the text to display");


Set Font

You can set the font of a JavaFX Text control via its setFont() method. Here is an example of setting the font
of a JavaFX Text object via its setFont() method:

Text text = new Text("Some Text");

text.setFont(Font.font("Arial"));
This example sets the font to be used by the Text control to render the text to be of the font family Arial.

The JavaFX Font class used in this example is the javafx.scene.text.Font class. The Font class actually also
lets you specify the font weight and font size. Here is the example above, modified to also set font weight
and font size for the JavaFX Text control:

Text text = new Text("Some Text");

text.setFont(Font.font("Arial", FontWeight.BOLD, 36));

This example sets the font weight to bold and font size to 36. The FontWeight class used in this example is
the javafx.scene.text.FontWeight class.

Set Fill Color

Being a Shape, you can set the fill color of a JavaFX Text control. The fill color is the "inside" color used to
draw the text. You set the fill color of a Text control via its setFill()method which takes a JavaFX
Color object as parameter. Here is an example of setting the fill color of a JavaFX Text control via setFill():

text.setFill(Color.YELLOW);
Set Stroke Color

Being a Shape, you can also set the stroke color of a JavaFX Text control. The stroke color is the "outline" or
"boundary" color used to draw the text. By default, text is rendered only using the fill color, but setting a
stroke color can add a nice effect. You set the stroke color of a Text control via its setStroke() method
which takes a JavaFX Colorobject as parameter. Here is an example of setting the stroke color of a JavaFX
Text control via setStroke():

text.setStroke(Color.GREEN);
Text X and Y Position

The X and Y position of a JavaFX Text control determines where inside its parent container element the
Text control is displayed - provided the parent container respects this position (Pane does, VBox does
not). You can set the X and Y position of a Text control via its methods setX() and setY(). Here is an
example of setting the X and Y position of a JavaFX Text control:

text.setX(50);
text.setY(25);
Text Origin

The JavaFX Text control has an origin which controls how the text is displayed relative to the Y position of
the Text control. You set the origin using the Text setTextOrigin()method. Here is an example of setting the
Text origin:
text.setTextOrigin(VPos.BASELINE);

The setTextOrigin() method takes a VPos parameter. The VPos class contains the following constants you
can choose between:

• VPos.BASELINE
• VPos.BOTTOM
• VPos.CENTER
• VPos.TOP

VPos.BASELINE means that the Y position of the Text control is interpreted to mean the Y baseline of the
displayed text. The text is displayed just above the baseline, with some characters extending below the
baseline.

VPos.BOTTOM means that the Y position of the Text control is interpreted to mean the bottom the
displayed text. This is lower than BASELINE.

VPos.CENTER means that the Y position of the Text control is interpreted to mean the center of the text
vertically.

VPos.TOP means that the Y position of the Text control is interpreted to mean the top of the text vertically.

Multiline Text

The JavaFX Text control will break the text it displays on to multiple lines based on these rules:

• If the text contains a line break ( \n ) .


• If the text width exceeds a wrapping width set on the Text control.

Here is first an example showing a text that contains a line break:

Text text = new Text("This is a JavaFX text.\nLine 2");

The Text control will break the text before "Line" because the String contains a line break character.

Here is an example of setting a text wrapping width on the JavaFX Text control:

Text text = new Text("This is a longer JavaFX text.");


text.setWrappingWidth(80);

The JavaFX Text control will attempt to break the text between words. Thus, if after a specific word the text
width is wider than the wrapping width, the Text control will wrap the text before that word that makes
the text wider than the wrapping width.

Text Strikethrough
The JavaFX Text control enables you to apply a strikethrough decoration to the text it displays. You enable
the strikethrough decoration via the Text setStrikethrough()method, passing a value of true as parameter.
A parameter value of false will disable the strikethrough effect. Here is an example of enabling the JavaFX
Text strikethroughdecoration via the setStrikethrough() method:

text.setStrikethrough(true);
Text Underline

The JavaFX Text control enables you to apply an underline decoration to the text it displays. You enable the
underline decoration via the Text setUnderline() method, passing a value of true as parameter. A
parameter value of false will disable the underline decoration. Here is an example of enabling the JavaFX
Text underlinedecoration via the setUnderline() method:

text.setUnderline(true);
Font Smoothing Techniques

The JavaFX Text control contains two different font smoothing (antialiasing) techniques you can choose
between. The first technique is called LCD, and the second is called GRAY. You can choose which font
smoothing technique the Text control should use via the setFontSmoothingType() method. Here are
examples of setting both LCD and GRAY as font smoothing technique on a JavaFX Text control:

text.setFontSmoothingType(FontSmoothingType.GRAY);

text.setFontSmoothingType(FontSmoothingType.LCD);

Which of the two font smoothing techniques fits best to your application you will have to experiment with.
2.8 ScrollPane

The JavaFX ScrollPane control is a container that has two scrollbars around the component it contains if
the component is larger than the visible area of the ScrollPane. The scrollbars enable the user to scroll
around the component shown inside the ScrollPane, so different parts of the component can be seen. The
JavaFX ScrollPane controls is represented by the JavaFX class javafx.scene.control.ScrollPane. Here is a
screenshot of a JavaFX ScrollPane with a JavaFX ImageView inside:

Create a ScrollPane

To use a JavaFX ScrollPane you must first create a ScrollPane instance. Here is an example of creating a
JavaFX ScrollPane instance:

ScrollPane scrollPane = new ScrollPane();


Set ScrollPane Content
Once you have created a JavaFX ScrollPane instance you can set the content you want it to display via
its setContent() method. Here is an example that sets a JavaFX ImageView as content of a
JavaFX ScrollPane:

ScrollPane scrollPane = new ScrollPane();

String imagePath = "images/aerial-beverage-caffeine-972533.jpg";


ImageView imageView = new ImageView(new Image(new FileInputStream(imagePath)));

scrollPane.setContent(imageView);
ScrollPane Viewport

The visible part of a JavaFX ScrollPane is called the ScrollPane viewport. As you scroll around the content
displayed inside the ScrollPane using the scrollbars, the viewport is moved around the content too, making
different parts of the content visible.

Content With Effects or Transforms

If the content (JavaFX control) you want to display inside the JavaFX ScrollPane uses effects or transforms,
you must first wrap these controls in a JavaFX Group. Otherwise the content won't be displayed correctly.

Pannable ScrollPane

By default the user can only navigate around the content displayed in a JavaFX ScrollPane using its
scrollbars. However, it is possible to make a JavaFX ScrollPanepannable. A pannable ScrollPane enables the
user to navigate its content by holding down the left mouse button and move the mouse around. This will
have the same effect as using the scrollbars. However, using panning you can move the content along both
X and Y axis simultaneously. This is not possible using the scrollbars, where the user can only operate one
scrollbar at a time.

To switch a JavaFX ScrollPane into pannable mode you must set its pannableProperty to the value true.
Here is an example of switching a JavaFX ScrollPane into pannable mode:

scrollPane.pannableProperty().set(true);
Fit To Width

The JavaFX ScrollPane fitToWidth property can make the ScrollPane fit its content to the width of
the ScrollPane viewport. To do so, the fitToWidth property must be set to the value true. This property is
ignored if the content node is not resizable. Here is an example of setting the
JavaFX ScrollPane fitToWidth property to true:

scrollPane.fitToWidthProperty().set(true);
Fit To Height

The JavaFX ScrollPane fitToHeight property can make the ScrollPane fit its content to the height of
the ScrollPane viewport. To do so, the fitToHeight property must be set to the value true. This property is
ignored if the content node is not resizable. Here is an example of setting the
JavaFX ScrollPane fitToHeight property to true:

scrollPane.fitToHeightProperty().set(true);
Showing and Hiding Scrollbars via ScrollBar Policies

It is possible to specify when the JavaFX ScrollPane is to show the vertical and horizontal scrollbars. You do
so via the ScrollPane hbarPolicyProperty and vbarPolicyProperty properties. These properties can be set
to one of the ScrollPane.ScrollBarPolicy enum values. You can choose from the
values ALWAYS, AS_NEEDED and NEVER. Here is an example of setting
the hbarPolicyProperty and vbarPolicyProperty to ScrollBarPolicy.NEVER:

scrollPane.hbarPolicyProperty().setValue(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.vbarPolicyProperty().setValue(ScrollPane.ScrollBarPolicy.NEVER);

The above example removes the vertical and horizonal scrollbar from the ScrollPane. Without the
scrollbars the user cannot use them to scroll around the content of the ScrollPane. However, if
the ScrollPane is in pannable mode (see earlier sections in this JavaFX ScrollPane tutorial) the user can still
grab the content and scroll around it with the mouse.

3. Layouts

Layouts are the top level container classes that define the UI styles for scene graph objects. Layout can be
seen as the parent node to all the other nodes. JavaFX provides various layout panes that support different
styles of layouts.

In JavaFX, Layout defines the way in which the components are to be seen on the stage. It basically
organizes the scene-graph nodes. We have several built-in layout panes in JavaFX that are HBox, VBox,
StackPane, FlowBox, AnchorPane, etc. Each Built-in layout is represented by a separate class which needs
to be instantiated in order to implement that particular layout pane.

All these classes belong to javafx.scene.layout package. javafx.scene.layout.Pane class is the base class for
all the built-in layout classes in JavaFX.

Layout Classes

javafx.scene.layout Package provides various classes that represents the layouts. The classes are described
in the table below.

Class Description
BorderPane Organizes nodes in top, left, right, centre and the bottom of the screen.
FlowPane Organizes the nodes in the horizontal rows according to the available horizontal
spaces. Wraps the nodes to the next line if the horizontal space is less than the total
width of the nodes
GridPane Organizes the nodes in the form of rows and columns.
HBox Organizes the nodes in a single row.
Pane It is the base class for all the layout classes.
StackPane Organizes nodes in the form of a stack i.e. one onto another
VBox Organizes nodes in a vertical column.
Steps to create layout

In order to create the layouts, we need to follow the following steps.

1. Instantiate the respective layout class, for example, HBox root = new HBox();
2. Setting the properties for the layout, for example, root.setSpacing(20);
3. Adding nodes to the layout object, for example, root.getChildren().addAll(<NodeObjects>);

3. 1 FlowPane

A JavaFX FlowPane is a layout component which lays out its child components either vertically or
horizontally, and which can wrap the components onto the next row or column if there is not enough space
in one row. The JavaFX FlowPane layout component is represented by the
class javafx.scene.layout.FlowPane

Creating a FlowPane

You create a JavaFX FlowPane via its constructor. Here is a JavaFX FlowPaneinstantiation example:

FlowPane flowpane = new FlowPane();


Adding Children to a FlowPane

You can add children to a FlowPane by obtaining its child collection and add adding the components to it
you want the FlowPane to layout. Here is an example of adding 3 buttons to a FlowPane:

Button button1 = new Button("Button Number 1");


Button button2 = new Button("Button Number 2");
Button button3 = new Button("Button Number 3");

FlowPane flowpane = new FlowPane();

flowpane.getChildren().add(button1);
flowpane.getChildren().add(button2);
flowpane.getChildren().add(button3);
Adding a FlowPane to the Scene Graph
To make a FlowPane visible you must add it to the JavaFX scene graph. To do so you must add
the FlowPane instance to a Scene object, or add the FlowPane to a layout component which is added to
a Scene object.

Here is an example of adding a JavaFX FlowPane to the scene graph:

package com.jenkov.javafx.layouts;

import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class FlowPaneExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");

Button button1 = new Button("Button Number 1");


Button button2 = new Button("Button Number 2");
Button button3 = new Button("Button Number 3");

FlowPane flowpane = new FlowPane();

flowpane.getChildren().add(button1);
flowpane.getChildren().add(button2);
flowpane.getChildren().add(button3);

Scene scene = new Scene(flowpane, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


Application.launch(args);
}
}

The application resulting from this application looks like the following screen shots. Notice how the
buttons flow down onto the next horizontal line when the window becomes too small to show them all in a
single horizontal row.
Horizontal and Vertical Spacing

You can set the horizontal and vertical spacing between the components shown inside a
JavaFX FlowPane using its setHGap() and setVGap() methods. Here is an example that shows how to set
the horizontal and vertical gap between components in a FlowPane :

flowpane.setHgap(10);
flowpane.setVgap(10);

When added to the example earlier, the resulting application would look like this:

Notice the horizontal and vertical gaps between the buttons now.

Orientation

By default the components in a FlowPane are layed out horizontally, wrapping onto the next horizontal
line when there is no longer space enough inside the FlowPane to show more components horizontally.
You can change the flow orientation (direction) of a FlowPane using its setOrientation()method. You can
force the components to be layed out in columns from top to bottom, and then change column when there
is no more space in the height to show more components. Here is how you do that:

flowpane.setOrientation(Orientation.VERTICAL);

The JavaFX Pane class is a layout container which can contain other JavaFX components internally, and lay
them out. Actually, the JavaFX Pane class does not actually provide any layout algorithm. The Pane class
simply displays the components it contains at the locations the components themselves want to be located.
In other words, the Pane class uses the layoutX and layoutY specified by its child components to determine
where to display them.

The JavaFX Pane class, javafx.scene.layout.Pane, is a subclass of the JavaFX Regionclass, so it inherits all of
the Region class functionality. That includes functionality like borders, padding, background settings etc.

Create a JavaFX Pane

You create a JavaFX Pane simply via its standard no-arg constructor. Here is an example of creating a
JavaFX Pane instance:

Pane pane = new Pane();

Add Items to a JavaFX Pane

You add items JavaFX Pane by obtaining its list of children via getChildren(), and then add the items to that
list. Here is an example of adding a JavaFX Label to a JavaFX Pane:

Pane pane = new Pane();

pane.getChildren().add(new Label("Hello Pane"));

If you repeat the last line multiple times, you will add multiple Label instances to the Pane. Just keep in
mind, that unless you change the layoutX and / or layoutY properties of the added Labels, all the Label
instances will be displayed in the same X and Y position - meaning on top of each other.

Adding a JavaFX Pane to the Scene Graph

Here is an example of adding a JavaFX Pane to the JavaFX scene graph - by setting the Pane as the root
node of a JavaFX Scene:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class PaneExample extends Application {

public static void main(String[] args) {


launch(args);
}

public void start(Stage primaryStage) {

Pane pane = new Pane();

pane.getChildren().add(new Label("Hello Pane"));

Scene scene = new Scene(pane);

primaryStage.setScene(scene);

primaryStage.show();
}
}

3.2 HBox and VBox

The JavaFX HBox component is a layout component which positions all its child nodes (components) in a
horizontal row. The Java HBox component is represented by the class javafx.scene.layout.HBox .

Create an HBox

You create an HBox using its constructor like this:

HBox hbox = new HBox();

HBox also has a constructor which takes a variable length list of components it should layout. Here is an
example of how to do that:

Button button1 = new Button("Button Number 1");


Button button2 = new Button("Button Number 2");

HBox hbox = new HBox(button1, button2);

This HBox example will layout the two Button instances next to each other in a horizontal row.
Adding an HBox to the Scene Graph

For an HBox to be visible it must be added to the scene graph. This means adding it to aScene object, or as
child of a layout which is attached to a Scene object.

Here is an example that attaches a JavaFX HBox with the two Button instances to the scene graph:

package com.jenkov.javafx.layouts;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class HBoxExperiments extends Application {

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

primaryStage.setTitle("HBox Experiment 1");

Button button1 = new Button("Button Number 1");


Button button2 = new Button("Button Number 2");

HBox hbox = new HBox(button1, button2);

Scene scene = new Scene(hbox, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


Application.launch(args);
}
}

The result of running the above JavaFX HBox example is an application that looks like this:
Notice that the two Button controls are kept on the same horizontal row even if there is not enough space
to show them in their fully preferred widths. The buttons do not "wrap" down on the next line.

Child Node Spacing

In the earlier example the HBox positioned the nodes (button controls) right next to each other. You can
make the HBox insert some space between its nested controls by providing the space in
the HBox constructor. Here is an example of setting the space between nested controls in an HBox:

HBox hbox = new HBox(20, button1, button2);

This example sets the spacing between the controls in the HBox layout component to 20.

You can also set the space between the nested controls using the setSpacing()meethod, like this:

hbox.setSpacing(50);

This example will set the spacing between nested controls to 50.

Child Node Margin

You can set the margin for child nodes of a JavaFX HBox using the static setMargin()method. Here is an
example of setting the margin around a JavaFX Button using thesetMargin() method:

Button button1 = new Button("Button 1");

HBox hbox = new HBox(button1);

HBox.setMargin(button1, new Insets(10, 10, 10, 10));

This example sets the margin around the Button inside the HBox to 10 on each side.

Child Node Alignment


Since the JavaFX HBox is a container component, meaning it contains other JavaFX components, you can
specify how the HBox is to align the components it contains. You do so via the
HBox setAlignment() method. Here is an example of setting the alignment of child nodes for a JavaFX
HBox:

hbox.setAlignment(Pos.BASELINE_CENTER);

This example will make the HBox position its child nodes along the baseline (vertically) of the vertical line,
and from the center of the line and out (horizontally).

The JavaFX VBox control supports the following alignment options:

Parameter Vertically Horizontally


Pos.BASELINE_LEFT Baseline Left
Pos.BASELINE_CENTER Baseline Center
Pos.BASELINE_RIGHT Baseline Right
Pos.BOTTOM_LEFT Bottom Left
Pos.BOTTOM_CENTER Bottom Center
Pos.BOTTOM_RIGHT Bottom Right
Pos.CENTER_LEFT Center Left
Pos.CENTER Center Center
Pos.CENTER_RIGHT Center Right
Pos.TOP_LEFT Top Left
Pos.TOP_CENTER Top Center
Pos.TOP_RIGHT Top Right
Child Node hgrow

You can specify whether a child node of an HBox should grow horizontally to fill any available space
available inside the HBox. You do so via the HBox setHgrow() static method. You have to specify which
child node the rule is set for. You do so by passing the child node as parameter to setHgrow(). You also
have to pass the horizontal expansion policy as parameter to setHgrow(). Here is an example of telling that
a child Button to expand horizontally if space is available inside the HBox:

Button button1 = new Button("Button 1");

HBox hbox = new HBox(button1);

HBox.setHgrow(button1, Priority.ALWAYS);
The Priority class contains the following constants you can use to set the expansion policy:

1. Policy.ALWAYS
2. Policy.SOMETIMES
3. Policy.NEVER

Please keep in mind that the HBox will only have extra horizontal space available if the HBox is wider than
the sum of the preferred widths of its children.

HBox Preferred Height

The default preferred height of an HBox is set to the same value as the largest preferred height of any of its
child nodes.

fillHeight

The JavaFX HBox fillHeight property can be used to tell the HBox control whether it should expand the
height of its children to fill out the whole height of the HBox, or keep its children at their preferred heights.

The fillHeight property only affects child components which heights can actually change. For instance, a
Button does not change its height by default. It's max height is set to its preferred height. However, you can
override that by setting the max height of the Button, or any other component you want to nest inside the
HBox, to a value different than its preferred value.

Here is an example showing how the fillHeight property works:

Button button1 = new Button("Button 1");


button1.setMaxHeight(99999.0D); //or Double.MAX_VALUE;

HBox hbox = new HBox(button1);

hbox.setFillHeight(true);

VBox

The JavaFX VBox component is a layout component which positions all its child nodes (components) in a
vertical column - on top of each other. The JavaFX VBox component is represented by the
class javafx.scene.layout.VBox . In this JavaFX VBox tutorial I will take a deeper look at the various options
the VBox component has for the layout of controls.

Create a VBox

To use the JavaFX VBox component you must first create an instance of the VBox class. You create
a VBox instance using its constructor like this:

VBox vbox = new VBox();


VBox also has a constructor which takes a variable length list of components it should layout. Here is an
example of how to do that:

Button button1 = new Button("Button Number 1");


Button button2 = new Button("Button Number 2");

VBox vbox = new VBox(button1, button2);

This VBox example will layout the two Button instances one on top of the other in a vertical column.

Adding a VBox to the Scene Graph

For a VBox instance to be visible it must be added to the scene graph. This means adding it to
a Scene object, or as child of another layout component which is attached to a Sceneobject.

Here is an example that attaches a JavaFX VBox with the two Button instances to the scene graph:

package com.jenkov.javafx.layouts;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class VBoxExperiments extends Application{

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

primaryStage.setTitle("VBox Experiment 1");

Button button1 = new Button("Button Number 1");


Button button2 = new Button("Button Number 2");

VBox vbox = new VBox(button1, button2);

Scene scene = new Scene(vbox, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


Application.launch(args);
}
}

The result of running the above JavaFX VBox example is an application that looks like this:

Child Node Spacing

In the earlier example the VBox positioned the nodes (button controls) right under the other. You can
make the VBox insert some space between its nested controls by providing the space in
the VBox constructor. Here is an example of setting the space between nested controls in an VBox:

VBox vbox = new VBox(20, button1, button2);

This example sets the spacing between the controls in the VBox layout component to 20.

You can also set the space between the nested controls using the setSpacing() method, like this:

vbox.setSpacing(50);

This example will set the spacing between nested controls to 50.

Child Node Alignment

Since the JavaFX VBox is a container component, meaning it contains other JavaFX components, you can
specify how the VBox is to align the components it contains. You do so via the
VBox setAlignment() method. Here is an example of setting the alignment of child nodes for a JavaFX VBox:

vbox.setAlignment(Pos.BASELINE_CENTER);

This example will make the VBox position its child nodes along the baseline (vertically) of the vertical line,
and from the center of the line and out (horizontally).

The JavaFX VBox control supports the following alignment options:

Parameter Vertically Horizontally


Pos.BASELINE_LEFT Baseline Left
Pos.BASELINE_CENTER Baseline Center
Pos.BASELINE_RIGHT Baseline Right
Pos.BOTTOM_LEFT Bottom Left
Pos.BOTTOM_CENTER Bottom Center
Pos.BOTTOM_RIGHT Bottom Right
Pos.CENTER_LEFT Center Left
Pos.CENTER Center Center
Pos.CENTER_RIGHT Center Right
Pos.TOP_LEFT Top Left
Pos.TOP_CENTER Top Center
Pos.TOP_RIGHT Top Right
Center Horizontally

You can use the child node alignment features to horizontally center the child nodes of a VBox. Here is an
example showing how to center the child nodes of a VBox horizontally:

vbox.setAlignment(Pos.BASELINE_CENTER);
Child Node Margin

You can set the margin for child nodes of a JavaFX VBox using the static setMargin()method. Here is an
example of setting the margin around a JavaFX Button using thesetMargin() method:

Button button = new Button("Button 1");

VBox vbox = new VBox(button);

VBox.setMargin(button, new Insets(10, 10, 10, 10));

This example sets the margin around the Button inside the VBox to 10 on each side.

Child Node vgrow

You can specify whether a child node of a VBox should grow vertically to fill any available space available
inside the VBox. You do so via the VBox setVgrow() static method. You have to specify which child node the
rule is set for. You do so by passing the child node as parameter to setVgrow(). You also have to pass the
vertical expansion policy as parameter to setVgrow(). Here is an example of telling that a child Button to
expand vertically if space is available inside the VBox:
Button button = new Button("Button 1");

VBox vbox = new VBox(button);

VBox.setVgrow(button, Priority.ALWAYS);

The Priority class contains the following constants you can use to set the expansion policy:

1. Policy.ALWAYS
2. Policy.SOMETIMES
3. Policy.NEVER

Please keep in mind that the VBox will only have extra vertical space available if the child nodes do not
have the same preferred height, or if you explicitly set a preferred height on the VBox that is larger than
the preferred height of its child nodes.

fillWidth

The JavaFX VBox fillWidth property can be used to tell the VBox control whether it should expand the
width of its children to fill out the whole width of the VBox, or keep its children at their preferred widths.

The fillWidth property only affects child components which widths can actually change. For instance, a
Button does not change its width by default. It's max width is set to its preferred width. However, you can
override that by setting the max width of the Button, or any other component you want to nest inside the
VBox, to a value different than its preferred value.

Here is an example showing how the fillWidth property works:

Button button = new Button("Button 1");


button.setMaxWidth(99999D); //or Double.MAX_VALUE;

VBox vbox = new VBox(button);

vbox.setFillWidth(true);
VBox CSS

Like many other JavaFX controls the VBox component can be styled via CSS. You set the CSS styles of the
JavaFX VBox component via its setStyle() method. Styling JavaFX controls via CSS is covered in more detail
in the JavaFX CSS Styling tutorial, but I will briefly explain how to style a JavaFX VBox here. Here is an
example of setting the CSS styles of a JavaFX VBox component:

vbox.setStyle("-fx-padding: 16;");

The VBox component supports the following CSS properties:


CSS Property Description
Sets the padding between the edge of the VBox and the edge of the outermost child
-fx-padding
nodes.
-fx-border-style Sets the border style of the VBox, in case you want a visible border around it.
-fx-border-width Sets the border width.
-fx-border-insets Sets the border insets.
-fx-border-
Sets the border radius (of corners).
radius
-fx-border-color Sets the border color.
VBox FXML

You can define a JavaFX VBox from inside a JavaFX FXML document. Here is an example of how a VBox
FXML definition looks:

<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<GridPane xmlns:fx="http://javafx.com/fxml"
fx:controller="sample.Controller"
alignment="center" hgap="10" vgap="10">

<VBox>
<Label>Text inside VBox</Label>
</VBox>

</GridPane>

Here are some of the most commonly used VBox XML element attributes:

• border
• alignment
• fillWidth

3.3 BorderPane

BorderPane arranges the nodes at the left, right, centre, top and bottom of the screen. It is represented
by javafx.scene.layout.BorderPane class. This class provides various methods like setRight(), setLeft(),
setCenter(), setBottom() and setTop() which are used to set the position for the specified nodes. We
need to instantiate BorderPane class to create the BorderPane layout.
Properties

The properties of BorderPane class along with their setter methods are given in the table below.

Type Property Setter Methods Description

Node Bottom setBottom() Add the node to the bottom of the screen

Node Centre setCentre() Add the node to the centre of the screen

Node Left setLeft() Add the node to the left of the screen

Node Right setRight() Add the node to the right of the screen

Node Top setTop() Add the node to the top of the screen

Constructors

There are the following constructors in the class.

1. BorderPane() : create the empty layout


2. BorderPane(Node Center) : create the layout with the center node
3. BorderPane(Node Center, Node top, Node right, Node bottom, Node left) : create the layout with all
the nodes

Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}

}
3.4 StackPane

The StackPane layout pane places all the nodes into a single stack where every new node gets placed on
the top of the previous node. It is represented by javafx.scene.layout.StackPaneclass. We just need to
instantiate this class to implement StackPane layout into our application.

Properties

The class contains only one property that is given below along with its setter method.

Property Description Setter Method

alignment It represents the default alignment of children within setAlignment(Node child,


the StackPane's width and height Pos value)
setAlignment(Pos value)

Constructors

The class contains two constructors that are given below.

1. StackPane()
2. StackPane(Node? Children)

Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Label_Test extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1 on bottom ");
Button btn2 = new Button("Button 2 on top");
StackPane root = new StackPane();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}

3.5 GridPane

A JavaFX GridPane is a layout component which lays out its child components in a grid. The size of the cells
in the grid depends on the components displayed in the GridPane, but there are some rules. All cells in the
same row will have the same height, and all cells in the same column will have the same width. Different
rows can have different heights and different columns can have different widths.

The JavaFX GridPane is different from the TilePane in that a GridPane allows different size of cells,
whereas a TilePane makes all tiles the same size.

The number of rows and columns in a GridPane depends on the components added to it. When you add a
component to a GridPane you tell in what cell (row, column) the component should be inserted, and how
many rows and columns the component should span.

The JavaFX GridPane layout component is represented by the class javafx.scene.layout.GridPane

Creating a GridPane

You create a JavaFX GridPane via its constructor. Here is a JavaFX GridPaneinstantiation example:

GridPane gridPane = new GridPane();


Adding Children to a GridPane

You can add children to a JavaFX GridPane in several ways. The easiest way is to use the add() of
the GridPane. Here is an example of adding 6 buttons to a GridPane:

Button button1 = new Button("Button 1");


Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
Button button4 = new Button("Button 4");
Button button5 = new Button("Button 5");
Button button6 = new Button("Button 6");

GridPane gridPane = new GridPane();

gridPane.add(button1, 0, 0, 1, 1);
gridPane.add(button2, 1, 0, 1, 1);
gridPane.add(button3, 2, 0, 1, 1);
gridPane.add(button4, 0, 1, 1, 1);
gridPane.add(button5, 1, 1, 1, 1);
gridPane.add(button6, 2, 1, 1, 1);

The first parameter of the add() method is the component (node) to add to the GridPane.

The second and third parameter of the add() method is the column index and row index of the cell in which
the component should be displayed. Column and row indexes start from 0.

The fourth and fifth parameter of the add() method are the oclumn span and row span of the component,
meaning how many rows and columns the component should extend to. Column span and row span works
similarly to colspan and rowspan in an HTML table.

Adding a GridPane to the Scene Graph

To make a JavaFX GridPane visible you must add it to the JavaFX scene graph. To do so you must add
the GridPane instance to a Scene object, or add the GridPane to a layout component which is added to
a Scene object.

Here is an example of adding a JavaFX GridPane to the scene graph:

package com.jenkov.javafx.layouts;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class GridPaneExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("GridPane Experiment");

Button button1 = new Button("Button 1");


Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
Button button4 = new Button("Button 4");
Button button5 = new Button("Button 5");
Button button6 = new Button("Button 6");

GridPane gridPane = new GridPane();

gridPane.add(button1, 0, 0, 1, 1);
gridPane.add(button2, 1, 0, 1, 1);
gridPane.add(button3, 2, 0, 1, 1);
gridPane.add(button4, 0, 1, 1, 1);
gridPane.add(button5, 1, 1, 1, 1);
gridPane.add(button6, 2, 1, 1, 1);

Scene scene = new Scene(gridPane, 240, 100);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


Application.launch(args);
}
}

The application resulting from this application looks like the following screen shots.

Spanning Multiple Rows and Columns

To see how to make a component span multiple columns and rows, look at this modification of the 6
buttons added to the GridPane:

gridPane.add(button1, 0, 0, 2, 2);

gridPane.add(button2, 2, 0, 1, 1);
gridPane.add(button3, 2, 1, 1, 1);
gridPane.add(button4, 0, 2, 1, 1);
gridPane.add(button5, 1, 2, 1, 1);
gridPane.add(button6, 2, 2, 1, 1);
Notice how the first button added is given a column span and row span of 2. Notice how the rest of the
buttons are added outside of the top left 2 x 2 columns. The layout resulting from these settings looks like
this:

Horizontal and Vertical Spacing

You can set the horizontal and vertical spacing between the components shown inside a
JavaFX GridPane using its setHGap() and setVGap() methods. Here is an example that shows how to set the
horizontal and vertical gap between components in a GridPane :

gridPane.setHgap(10);
gridPane.setVgap(10);

When added to the example earlier, the resulting application would look like this:

Notice the horizontal and vertical gaps between the buttons. If there were no gaps set on the GridPane the
buttons would have been positioned next to each other.

4. Menus

The JavaFX MenuBar provides JavaFX applications with a visual drop down menu similar to that most
desktop applications have at the top of their application window. The JavaFX MenuBar is represented by
the class javafx.scene.control.MenuBar . Here is an example screenshot of what a JavaFX MenuBar can look
like:
Creating a MenuBar Instance

Before you can use the JavaFX MenuBar you must create a MenuBar instance. Here is an example of
creating a JavaFX MenuBar instance:

MenuBar menuBar = new MenuBar();


Adding a MenuBar to the Scene Graph

Before a MenuBar becomes visible you will have to add it to the JavaFX scene graph. Here is an example of
adding a JavaFX MenuBar to the scene graph:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXApp extends Application {

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX App");

MenuBar menuBar = new MenuBar();


VBox vBox = new VBox(menuBar);

Scene scene = new Scene(vBox, 960, 600);

primaryStage.setScene(scene);
primaryStage.show();
}
}

Notice how the MenuBar is added to the root layout (VBox) of the JavaFX scene. This places the MenuBar at
the top of the application window.

Note that the above example does not add any menus or menu items to the MenuBar, so if you run the
example you will not actually see the MenuBar. We will see how to add menus and menu items in the
following sections.

Creating Menu Instances

Once the MenuBar instance is created, you can add Menu instances to it (javafx.scene.control.Menu .
A Menu instance represents a single vertical menu with nested menu items. Thus, you can add
multiple MenuBar instances to a MenuBar to add multiple vertical drop down menus.

Here is an example of adding a Menu to a MenuBar :

Menu menu1 = new Menu("Menu 1");

MenuBar menuBar = new MenuBar();

menuBar.getMenus().add(menu1);

Here is a screenshot showing the JavaFX MenuBar as configured by the example code above:

As you can see, there is only a single menu in the MenuBar titled "Menu 1" . This menu has no menu items
nested under it. We will see how to add menu items to a Menu in the following sections.

Menu Graphics
You can set a graphic icon for a Menu by calling its setGraphic() method. The graphic icon will be displayed
next to the text label of the menu. Here is an example of setting a graphic icon for a JavaFX Menu instance:

Menu menu = new Menu("Menu 1");


menu.setGraphic(new ImageView("file:volleyball.png"));

Here is how the resulting menu could look in a JavaFX application:

Menu Events

A JavaFX Menu instance can fire several events which you can listen for in your application. The most
commonly used events are:

• onShowing
• onShown
• onHiding
• onHidden

When a Menu is clicked with the mouse it shows its contents. This action fires the eventonShowing before
the Menu starts showing its menu items. Once the menu is fully visible the onShown event is fired.

When an shown (open) Menu is clicked with the mouse it hides its contents again. This action fires the
event onHiding before the Menu starts hiding its menu items. Once the menu is fully hidden
the onHidden event is fired.

You can set Menu event listeners for the events above using the
methods setOnShowing(), setOnShown(), setOnHiding() and setOnHidden(). Here is an example of setting
event listeners for these events on a JavaFX Menu :

Menu menu = new Menu("Menu 1");

menu.setOnShowing(e -> { System.out.println("Showing Menu 1"); });


menu.setOnShown (e -> { System.out.println("Shown Menu 1"); });
menu.setOnHiding (e -> { System.out.println("Hiding Menu 1"); });
menu.setOnHidden (e -> { System.out.println("Hidden Menu 1"); });

The Menu event listeners set above only print out a message to the console when the events fired. You
could do something more advanced in case you needed to.

Adding Menu Items

Once you have created a Menu instance you must add one or more MenuItem instances to it.
Each MenuItem corresponds to a menu item in the menu it is added to. Here is an example of adding
2 MenuItem instances to a Menu, which is then added to a MenuBar:

Menu menu = new Menu("Menu 1");


MenuItem menuItem1 = new MenuItem("Item 1");
MenuItem menuItem2 = new MenuItem("Item 2");

menu.getItems().add(menuItem1);
menu.getItems().add(menuItem2);

MenuBar menuBar = new MenuBar();


menuBar.getMenus().add(menu);

Here is what the resulting JavaFX MenuBar would look like, if used in a JavaFX application:

MenuItem Graphics

You can add an icon to a menu item. You add a graphic icon to a MenuItem by calling
itssetGraphic() method, passing as parameter the graphic you want to use for the given MenuItem. Here is
an example that adds images to the menu items created in the example in the previous section:

Menu menu = new Menu("Menu 1");

MenuItem menuItem1 = new MenuItem("Item 1");


menuItem1.setGraphic(new ImageView("file:soccer.png"));

MenuItem menuItem2 = new MenuItem("Item 2");


menuItem1.setGraphic(new ImageView("file:basketball.png"));

menu.getItems().add(menuItem1);
menu.getItems().add(menuItem2);

MenuBar menuBar = new MenuBar();


menuBar.getMenus().add(menu);

Here is how a JavaFX MenuBar looks with graphic icons added to its menu items:

MenuItem Events

The MenuBar configurations created in the previous examples do not react if you select any of the menu
items. In order to respond to the selection of a MenuItem you must set an event listener on the MenuItem.
Here is an example of adding an event listener to a JavaFX MenuItem:

MenuItem menuItem1 = new MenuItem("Item 1");

menuItem1.setOnAction(e -> {
System.out.println("Menu Item 1 Selected");
});

Notice the Java Lambda added as parameter to the setOnAction() method of the MenuItem . This lambda
expression is executed when the menu item is selected.

Submenus

The JavaFX MenuBar supports multiple layers of menus. A menu nested inside another menu is called a
submenu. The Menu class extends the MenuItem class and can therefore be used as a menu item inside
another Menu instance. Here is an example that creates a single JavaFX menu with a submenu inside:

Menu menu = new Menu("Menu 1");


Menu subMenu = new Menu("Menu 1.1");
MenuItem menuItem11 = new MenuItem("Item 1.1.1");
subMenu.getItems().add(menuItem11);
menu.getItems().add(subMenu);

MenuItem menuItem1 = new MenuItem("Item 1");


menu.getItems().add(menuItem1);

MenuItem menuItem2 = new MenuItem("Item 2");


menu.getItems().add(menuItem2);

MenuBar menuBar = new MenuBar();


menuBar.getMenus().add(menu);

The JavaFX MenuBar resulting from the above example will look similar to this:

Check Menu Items

The JavaFX MenuBar supports using check menu items in a menu. A check menu item is a menu item that
can be "selected" and remain selected until unselected later. A small check mark is displayed next to the
check menu item as long as it remains selected.

The check menu item is represented by the CheckMenuItem(javafx.scene.control.CheckMenuItem) class.


Here is an example of a JavaFX menu with a CheckMenuItem in:

CheckMenuItem checkMenuItem = new CheckMenuItem("Check this!");

menu.getItems().add(checkMenuItem);

The Menu instance then need to be added to a MenuBar to be visible, as you have seen in earlier examples.
Here is how the resulting menu looks, with the check menu menu item checked:
Radio Menu Item

The JavaFX MenuBar also supports radio menu items. Radio menu items are menu items of which only one
of a set of menu items can be selected - just like standard JavaFX radio buttons.

The radio menu item is represented by the RadioMenuItem. The RadioMenuItem instance must be added
to a ToggleGroup to make them mutually exclusive. That is how JavaFX knows
which RadioMenuItem instance belong together. Here is an example of a JavaFx menu that uses a set of
radio menu items:

Menu menu = new Menu("Menu 1");

RadioMenuItem choice1Item = new RadioMenuItem("Choice 1");


RadioMenuItem choice2Item = new RadioMenuItem("Choice 2");
RadioMenuItem choice3Item = new RadioMenuItem("Choice 3");

ToggleGroup toggleGroup = new ToggleGroup();


toggleGroup.getToggles().add(choice1Item);
toggleGroup.getToggles().add(choice2Item);
toggleGroup.getToggles().add(choice3Item);

menu.getItems().add(choice1Item);
menu.getItems().add(choice2Item);
menu.getItems().add(choice3Item);

MenuBar menuBar = new MenuBar();


menuBar.getMenus().add(menu);

Here is how the JavaFx menu resulting from this example code looks:
Menu Item Separators

The MenuBar supports menu item separators. A separator is a horizontal line that separates groups of
menu items. A separator is often used to signal to users what menu items are related to each other.

Menu item separators are represented by the SeparatorMenuItem class. Here is an example of a menu with
two menu items separated by a SeparatorMenu:

MenuItem item1 = new MenuItem("Item 1");


MenuItem item2 = new MenuItem("Item 2");
SeparatorMenuItem separator = new SeparatorMenuItem();

menu.getItems().add(item1);
menu.getItems().add(separator);
menu.getItems().add(item2);

MenuBar menuBar = new MenuBar();


menuBar.getMenus().add(menu);

Here is how the resulting JavaFX menu would look like:


Custom Control Menu Items

The JavaFX MenuBar also supports using custom JavaFX controls as menu items. To do so you need to use
the CustomMenuItem (javafx.scene.control.CustomMenuItem) class.

The CustomMenuItem class has a setContent() method which you can use to set the custom JavaFX control
to show in the menu. Here is an example that shows both a JavaFX Button and a JavaFX Slider as custom
menu items:

Menu menu = new Menu("Menu 1");

Slider slider = new Slider(0, 100, 50);

CustomMenuItem customMenuItem = new CustomMenuItem();


customMenuItem.setContent(slider);
customMenuItem.setHideOnClick(false);
menu.getItems().add(customMenuItem);

Button button = new Button("Custom Menu Item Button");


CustomMenuItem customMenuItem2 = new CustomMenuItem();
customMenuItem2.setContent(button);
customMenuItem2.setHideOnClick(false);
menu.getItems().add(customMenuItem2);

MenuBar menuBar = new MenuBar();


menuBar.getMenus().add(menu);

Notice the call to CustomMenuItem setHideOnClick() with the value false as parameter. This is done to
keep the menu open while the user interacts with the custom menu item control. If you set the value
to true the menu will close as soon as the user clicks the control the first time, making further interaction
impossible. For normal menu items you actually do want the menu to close immediately, but for some
custom menu items you may not want that. The menu can still be closed by clicking on the menu title
again.

Here is how the resulting menu looks:


Creating a MenuButton

You create a JavaFX MenuButton by creating an instance of the MenuButton class. The MenuButton
constructor takes a button text and a button graphic. You can pass null for the text and / or the graphic, in
case you want a MenuButton without either text or graphic. Here is an example of creating a
JavaFX MenuButton with only a text label:

MenuItem menuItem1 = new MenuItem("Option 1");


MenuItem menuItem2 = new MenuItem("Option 2");
MenuItem menuItem3 = new MenuItem("Option 3");

MenuButton menuButton = new MenuButton("Options", null, menuItem1, menuItem2, menuItem3);

First 3 MenuItem instances are created, each with a different text. Then a MenuButton instance is created,
passing a button text, a graphic icon (null) and the 3 MenuItem instances as parameter to
the MenuButton constructor.

The second MenuButton constructor parameter is a Node which is used as a graphic icon which is shown
next to the MenuButton text. You could use an ImageView control to display an an image next to the
MenuButton text. Just create an ImageView instance and pass a reference to that to
the MenuButton constructor, instead of null. Here is an example:

MenuItem menuItem1 = new MenuItem("Option 1");


MenuItem menuItem2 = new MenuItem("Option 2");
MenuItem menuItem3 = new MenuItem("Option 3");

FileInputStream input = new FileInputStream("resources/images/iconmonstr-menu-5-32.png");


Image image = new Image(input);
ImageView imageView = new ImageView(image);
MenuButton menuButton = new MenuButton("Options", imageView, menuItem1, menuItem2,
menuItem3);
Adding a MenuButton to the Scene Graph

To make a MenuButton visible you must add it to the JavaFX scene graph. This means adding it to a Scene,
or as child of a layout which is attached to a Scene object.

Here is an example that attaches a JavaFX MenuButton to the scene graph:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.io.FileInputStream;

public class MenuButtonExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ImageView Experiment 1");

MenuItem menuItem1 = new MenuItem("Option 1");


MenuItem menuItem2 = new MenuItem("Option 2");
MenuItem menuItem3 = new MenuItem("Option 3");

MenuButton menuButton = new MenuButton("Options", null, menuItem1, menuItem2, menuItem3);

HBox hbox = new HBox(menuButton);

Scene scene = new Scene(hbox, 200, 100);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


Application.launch(args);
}

}
Here is how the application resulting from the above example looks:

MenuButton Font

You can specify what font the text label on a JavaFX MenuButton should be rendered with. You set the font
via the MenuButton setFont() method. Here is an example of setting the font of a JavaFX MenuButton
via setFont():

MenuItem menuItem1 = new MenuItem("Option 1");


MenuItem menuItem2 = new MenuItem("Option 2");

MenuButton menuButton = new MenuButton("Options", null, menuItem1, menuItem2);

Font font = Font.font("Courier New", FontWeight.BOLD, 36);


menuButton.setFont(font);
MenuButton Icon

The JavaFX MenuButton enables you to add a graphical icon which is then displayed next to the menu text -
just like you can do with a regular JavaFX Button. The second example in the "Create a MenuButton"
section shows how to create a MenuButton and pass the graphical icon via the constructor. However, it is
also possible to set the graphical icon of a MenuButton via its setGraphic() method. Here is how the
example from the previous section would look with a graphic icon added to the MenuButton via
its setGraphic() method:

package com.jenkov.javafx.controls;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.io.FileInputStream;
public class MenuButtonExperiments extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ImageView Experiment 1");

MenuItem menuItem1 = new MenuItem("Option 1");


MenuItem menuItem2 = new MenuItem("Option 2");
MenuItem menuItem3 = new MenuItem("Option 3");

MenuButton menuButton = new MenuButton("Options", null, menuItem1, menuItem2, menuItem3);

FileInputStream input = new FileInputStream("resources/images/iconmonstr-menu-5-32.png");


Image image = new Image(input);
ImageView imageView = new ImageView(image);

menuButton.setGraphic(imageView);

HBox hbox = new HBox(menuButton);

Scene scene = new Scene(hbox, 200, 160);


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


Application.launch(args);
}

Here is how the application resulting from the above example looks:
Responding to Menu Item Selection

To respond to when a user selects a menu item, add an "on action" event listener to the
corresponding MenuItem object. Here is an example showing you how to add an action event listener to
a MenuItem object:

MenuItem menuItem3 = new MenuItem("Option 3");

menuItem3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Option 3 selected");
}
});

You can also use a Java Lambda expression instead of an anonymous implementation of
the EventHandler interface. Here is how that looks:

menuItem3.setOnAction(event -> {
System.out.println("Option 3 selected via Lambda");
});

You might also like