Cs3391 Oops Unit V
Cs3391 Oops Unit V
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.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.
• 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.
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.
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.
Quantum Tool Kit is used to bind prism and glass windowing tool kit together and makes them available
for the above layers in stack.
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.
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.
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.
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();
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();
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);
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;
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;
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.
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);
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;
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;
@Override
public void start(Stage stage) {
//Drawing a Box
Box box = new Box();
@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);
//Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);
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.
Convenience methods for registering event handlers have the following format:
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:
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.
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;
/**
* @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>() {
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;
primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 500, 500);
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);
}
}
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;
primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 500, 500);
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.
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")
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 {
@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:
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.
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
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.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.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.
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
toggleButton1.setToggleGroup(toggleGroup);
toggleButton2.setToggleGroup(toggleGroup);
toggleButton3.setToggleGroup(toggleGroup);
toggleButton4.setToggleGroup(toggleGroup);
ToggleButton selectedToggleButton =
(ToggleButton) toggleGroup.getSelectedToggle();
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 .
Creating a RadioButton
You create a JavaFX RadioButton using its constructor. Here is a JavaFX RadioButtoninstantiation example:
The String passed as parameter to the RadioButton constructor is displayed next to theRadioButton.
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.
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
The application resulting from running this example looks like this:
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:
You can group JavaFX RadioButton instances into a ToggleGroup. A ToggleGroup allows at most
one RadioButton to be selected at any time.
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;
radioButton1.setToggleGroup(radioGroup);
radioButton2.setToggleGroup(radioGroup);
radioButton3.setToggleGroup(radioGroup);
radioButton4.setToggleGroup(radioGroup);
The application resulting from running this example looks like this:
You can read which RadioButton of a ToggleGroup is selected using thegetSelectedToggle() method, like
this:
RadioButton selectedRadioButton =
(RadioButton) toggleGroup.getSelectedToggle();
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:
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;
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
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.
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
button.setOnAction(event -> {
ObservableList selectedIndices = listView.getSelectionModel().getSelectedIndices();
for(Object o : selectedIndices){
System.out.println("o = " + o + " (" + o.getClass() + ")");
}
});
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
button.setOnAction(event -> {
ObservableList selectedIndices = listView.getSelectionModel().getSelectedIndices();
for(Object o : selectedIndices){
System.out.println("o = " + o + " (" + o.getClass() + ")");
}
});
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ComboBox Experiment 1");
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from running this example would look similar to this:
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:
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.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();
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:
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ChoiceBox Experiment 1");
choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");
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():
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.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();
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.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
}
}
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():
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.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:
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.
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:
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:
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.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.
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
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:
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:
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.
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
flowpane.getChildren().add(button1);
flowpane.getChildren().add(button2);
flowpane.getChildren().add(button3);
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.
You create a JavaFX Pane simply via its standard no-arg constructor. Here is an example of creating a
JavaFX Pane instance:
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:
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.
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;
primaryStage.setScene(scene);
primaryStage.show();
}
}
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
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:
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;
@Override
public void start(Stage primaryStage)
throws Exception {
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.
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:
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.
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:
This example sets the margin around the Button inside the HBox to 10 on each side.
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).
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:
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.
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.
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:
This VBox example will layout the two Button instances one on top of the other in a vertical column.
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;
@Override
public void start(Stage primaryStage)
throws Exception {
The result of running the above JavaFX VBox example is an application that looks like this:
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:
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.
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).
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:
This example sets the margin around the Button inside the VBox to 10 on each side.
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.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.
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;");
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.
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
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.
Constructors
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.
Creating a GridPane
You create a JavaFX GridPane via its constructor. Here is a JavaFX GridPaneinstantiation example:
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:
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.
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.
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("GridPane Experiment");
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 application resulting from this application looks like the following screen shots.
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:
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:
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;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX App");
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.
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.
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 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 :
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.
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.getItems().add(menuItem1);
menu.getItems().add(menuItem2);
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.getItems().add(menuItem1);
menu.getItems().add(menuItem2);
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:
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:
The JavaFX MenuBar resulting from the above example will look similar to this:
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.
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.getItems().add(choice1Item);
menu.getItems().add(choice2Item);
menu.getItems().add(choice3Item);
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:
menu.getItems().add(item1);
menu.getItems().add(separator);
menu.getItems().add(item2);
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:
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.
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:
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:
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.
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;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ImageView Experiment 1");
}
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():
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");
menuButton.setGraphic(imageView);
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:
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");
});