0% found this document useful (0 votes)
53 views

Unit V Javafx Event Ndling

This document provides information about JavaFX, including its features, history, architecture, API packages, scene graph, and Prism graphics pipeline. It discusses that JavaFX is a Java library used to build rich internet applications running across platforms. It has built-in UI controls, CSS styling, canvas and printing APIs. The document outlines the history of JavaFX and describes its architecture including the public API layer and underlying components. It also discusses the scene graph structure and Prism graphics rendering pipeline used in JavaFX.

Uploaded by

Dazzling King
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)
53 views

Unit V Javafx Event Ndling

This document provides information about JavaFX, including its features, history, architecture, API packages, scene graph, and Prism graphics pipeline. It discusses that JavaFX is a Java library used to build rich internet applications running across platforms. It has built-in UI controls, CSS styling, canvas and printing APIs. The document outlines the history of JavaFX and describes its architecture including the public API layer and underlying components. It also discusses the scene graph structure and Prism graphics rendering pipeline used in JavaFX.

Uploaded by

Dazzling King
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/ 40

UNIT V JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS 9

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.

What is JavaFX?
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.
owing are some of the important features of JavaFX −
 Written in Java − The JavaFX library is written in Java and is available for the
languages that can be executed on a JVM.
 FXML − JavaFX features a language known as FXML, which is a HTML like
declarative markup language.
 Scene Builder − JavaFX provides an application named Scene Builder. On integrating
this application in IDE’s such as Eclipse and NetBeans, the users can access a drag and
drop design interface, which is used to develop FXML applications.
 Swing Interoperability − In a JavaFX application, you can embed Swing content using
the Swing Node class.
 Built-in UI controls − JavaFX library caters UI controls using which we can develop a
full-featured application.
 CSS like Styling − JavaFX provides a CSS like styling. By using this, you can improve
the design of your application with a simple knowledge of CSS.
 Canvas and Printing API − JavaFX provides Canvas, an immediate mode style of
rendering API. Within the package javafx.scene.canvas it holds a set of classes for
canvas, using which we can draw directly within an area of the JavaFX scene.
JavaFX also provides classes for Printing purposes in the package javafx.print.
 Rich set of API’s − JavaFX library provides a rich set of API’s to develop GUI
applications, 2D and 3D graphics, etc.
 Integrated Graphics library − JavaFX provides classes for 2d and 3d graphics.
 Graphics pipeline − JavaFX supports graphics based on the Hardware-accelerated
graphics pipeline known as Prism. When used with a supported Graphic Card or GPU
it offers smooth graphics.
History of JavaFX
JavaFX was originally developed by Chris Oliver, when he was working for a company
named See Beyond Technology Corporation, which was later acquired by Sun
Microsystems in the year 2005.
The following points give us more information of this project −
 Initially this project was named as F3 (Form Follows Functions) and it was developed
with an intention to provide richer interfaces for developing GUI Applications.
 Sun Microsystems acquired the See Beyond company in June 2005, it adapted the F3
project as JavaFX.

1
 In the year 2007, JavaFX was announced officially at Java One, a world wide web
conference which is held yearly.
 In the year 2008, Net Beans integrated with JavaFX was available. In the same year,
the Java Standard Development Kit for JavaFX 1.0 was released.
 In the year 2009, Oracle Corporation acquired Sun Microsystems and in the same year
the next version of JavaFX (1.2) was released as well.
 In the year 2010, JavaFX 1.3 came out and in the year 2011 JavaFX 2.0 was released.
 The latest version, JavaFX8, was released as an integral part of Java on 18th of March
2014.
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

2
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


JavaFX provides a complete API with a rich set of classes and interfaces to build GUI
applications with rich graphics. The important packages of this API are −
 javafx.animation − Contains classes to add transition based animations such as fill,
fade, rotate, scale and translation, to the JavaFX nodes.

3
 javafx.application − Contains a set of classes responsible for the JavaFX application
life cycle.
 javafx.css − Contains classes to add CSS–like styling to JavaFX GUI applications.
 javafx.event − Contains classes and interfaces to deliver and handle JavaFX events.
 javafx.geometry − Contains classes to define 2D objects and perform operations on
them.
 javafx.stage − This package holds the top level container classes for JavaFX
application.
 javafx.scene − This package provides classes and interfaces to support the scene graph.
In addition, it also provides sub-packages such as canvas, chart, control, effect, image,
input, layout, media, paint, shape, text, transform, web, etc.
The following illustration shows the architecture of JavaFX API. Here you can see the
components that support JavaFX API
Scene Graph
In JavaFX, the GUI Applications were coded using a Scene Graph. A Scene Graph is the
starting point of the construction of the GUI Application. It holds the (GUI) application
primitives that are termed as nodes.
A node is a visual/graphical object and it 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.
In general, a collection of nodes makes a scene graph. All these nodes are arranged in a
hierarchical order as shown below.

Each node in the scene graph has a single parent, and the node which does not contain any
parents is known as the root node.
In the same way, every node has one or more children, and the node without children is termed
as leaf node; a node with children is termed as a branch node.
A node instance can be added to a scene graph only once.
The nodes of a scene graph can have Effects, Opacity, Transforms, Event Handlers, Event
Handlers, Application Specific States.
Prism
Prism is a high performance hardware–accelerated graphical pipeline that is used to render
the graphics in JavaFX. It can render both 2-D and 3-D graphics.
To render graphics, a Prism uses −
 DirectX 9 on Windows XP and Vista.

4
 DirectX 11 on Windows 7.
 OpenGL on Mac and Linux, Embedded Systems.
In case the hardware support for graphics on the system is not sufficient, then Prism uses the
software render path to process the graphics.
GWT (Glass Windowing Toolkit)
As the name suggests, GWT provides services to manage Windows, Timers, Surfaces and
Event Queues. GWT connects the JavaFX Platform to the Native Operating System.
Quantum Toolkit
It is an abstraction over the low-level components of Prism, Glass, Media Engine, and Web
Engine. It ties Prism and GWT together and makes them available to JavaFX.
WebView
Using JavaFX, you can also embed HTML content in to a scene graph.
WebView is the component of JavaFX which is used to process this content. It uses a
technology called Web Kit, which is an internal open-source web browser engine. Using
WebView, you can −
 Render HTML content from local or remote URL.
 Support history and provide Back and Forward navigation.
 Reload the content.
 Apply effects to the web component.
 Edit the HTML content.
 Execute JavaScript commands.
 Handle events.
In general, using WebView, you can control web content from Java.
Media Engine
The JavaFX media engine is based on an open-source engine known as a Streamer. This
media engine supports the playback of video and audio content.
The JavaFX media engine provides support for audio for the following file formats −

The package javafx.scene.media contains the classes and interfaces to provide media
functionality in JavaFX. It is provided in the form of three components, which are −
 Media Object − This represents a media file
 Media Player − To play media content.
 Media View − To display media.

JavaFX Application Structure


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

5
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.

6
 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.
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);
}
}
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.

7
 The launcher waits for the application to finish and calls the stop() method.

Controls:
Every user interface considers the following three main aspects −
 UI elements − These are the core visual elements which the user eventually sees and
interacts with. JavaFX provides a huge list of widely used and common elements
varying from basic to complex, which we will cover in this tutorial.
 Layouts − They define how UI elements should be organized on the screen and provide
a final look and feel to the GUI (Graphical User Interface). This part will be covered in
the Layout chapter.
 Behavior − These are events which occur when the user interacts with UI elements.
This part will be covered in the Event Handling chapter.
JavaFX provides several classes in the package javafx.scene.control. To create various GUI
components (controls), JavaFX supports several controls such as date picker, button text field,
etc.
Each control is represented by a class; you can create a control by instantiating its respective
class.
Following is the list of commonly used controls while the GUI is designed using JavaFX.
S.No Control & Description

1 Label
A Label object is a component for placing text.

2 Button
This class creates a labeled button.

3 ColorPicker
A ColorPicker provides a pane of controls designed to allow a user to manipulate and select
a color.

4 CheckBox
A CheckBox is a graphical component that can be in either an on(true) or off (false) state.

5 RadioButton
The RadioButton class is a graphical component, which can either be in a ON (true) or
OFF (false) state in a group.

6 ListView
A ListView component presents the user with a scrolling list of text items.

7 TextField
A TextField object is a text component that allows for the editing of a single line of text.

8 PasswordField
A PasswordField object is a text component specialized for password entry.

9 Scrollbar
A Scrollbar control represents a scroll bar component in order to enable user to select from
range of values.

8
10 FileChooser
A FileChooser control represents a dialog window from which the user can select a file.

11 ProgressBar
As the task progresses towards completion, the progress bar displays the task's percentage
of completion.

12 Slider
A Slider lets the user graphically select a value by sliding a knob within a bounded interval.

JavaFX 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.
package 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);

9
primaryStage.setScene(scene);
primaryStage.setTitle("CheckBox Example");
primaryStage.show();
}
}
Output:

ToggleButton
A button is a component, which performs an action (like submit, login, etc..) when pressed.
It is usually labeled with a text or an image specifying the respective action.
A toggle button indicates whether it is elected or not, using toggle button(s) you can switch
between multiple states. Generally, multiple toggle buttons are grouped and you can select
only one at a time.
You can create a toggle button in JavaFX by instantiating
the javafx.scene.control.ToggleButton class. You can assign a toggle button to a group using
the setToggleGroup() method.
Only one button will be selected in a toggle group, unlike the radio button if you click on the
selected toggle button it will be un-selected.
Example
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ToggledButtonExample extends Application {
@Override
public void start(Stage stage) {
//Creating toggle buttons
ToggleButton button1 = new ToggleButton("Java");
ToggleButton button2 = new ToggleButton("Python");
ToggleButton button3 = new ToggleButton("C++");
//Toggle button group
ToggleGroup group = new ToggleGroup();
button1.setToggleGroup(group);
button2.setToggleGroup(group);
button3.setToggleGroup(group);
//Adding the toggle button to the pane
VBox box = new VBox(5);

10
box.setFillWidth(false);
box.setPadding(new Insets(5, 5, 5, 50));
box.getChildren().addAll(button1, button2, button3);
//Setting the stage
Scene scene = new Scene(box, 595, 150, Color.BEIGE);
stage.setTitle("Toggled Button Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Output

RadioButtons
A button is a component, which performs an action (like submit, login, etc..) when pressed.
It is usually labeled with a text or an image specifying the respective action.
A radio button is a type of button, which is circular in shape. It has two states, selected and
deselected. Generally, radio buttons are grouped using toggle groups, where you can only
select one of them.
You can create a radio button in JavaFX by instantiating
the javafx.scene.control.RadioButton class, which is the subclass of the ToggleButton class.
Action is generated whenever a radio button is pressed or released.
You can set a radio button to a group using the setToggleGroup() method.
Example
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class RadioButtonExample extends Application {
@Override
public void start(Stage stage) {
//Creating toggle buttons
RadioButton button1 = new RadioButton("Java");
RadioButton button2 = new RadioButton("Python");
RadioButton button3 = new RadioButton("C++");
//Toggle button group
ToggleGroup group = new ToggleGroup();

11
button1.setToggleGroup(group);
button2.setToggleGroup(group);
button3.setToggleGroup(group);
//Adding the toggle button to the pane
VBox box = new VBox(5);
box.setFillWidth(false);
box.setPadding(new Insets(5, 5, 5, 50));
box.getChildren().addAll(button1, button2, button3);
//Setting the stage
Scene scene = new Scene(box, 595, 150, Color.BEIGE);
stage.setTitle("Toggled Button Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Output

ListView
A list view is a scrollable list of items from which you can select desired items. You can create
a list view component by instantiating the javafx.scene.control.ListView class. You can
create either a vertical or a horizontal ListView.
Example
Following the JavaFX program demonstrates the creation of a ListView.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class ListViewExample extends Application {
public void start(Stage stage) {
//Label for education
Label label = new Label("Educational qualification:");

12
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
//list View for educational qualification
ObservableList<String> names = FXCollections.observableArrayList("Engineering",
"MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> listView = new ListView<String>(names);
listView.setMaxSize(200, 160);
//Creating the layout
VBox layout = new VBox(10);
layout.setPadding(new Insets(5, 5, 5, 50));
layout.getChildren().addAll(label, listView);
layout.setStyle("-fx-background-color: BEIGE");
//Setting the stage
Scene scene = new Scene(layout, 595, 200);
stage.setTitle("List View Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Output

ComboBox
A combo box is similar to a choice box it holds multiple items and, allows you to select one
of them. It can be formed by adding scrolling to a drop-down list. You can create a combo box
by instantiating the javafx.scene.control.ComboBox class.
Example
The following Example demonstrates the creation of a ComboBox.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;

13
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
public class ComboBoxExample extends Application {
public void start(Stage stage) {
//Setting the label
Label label = new Label("Select Desired Course:");
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
//Creating a combo box
ComboBox<String> combo = new ComboBox<String>();
//Setting the prompt text of the combo box
combo.setPromptText("Select Course");
//Getting the observable list of the combo box
ObservableList<String> list = combo.getItems();
//Adding items to the combo box
list.add("Java");
list.add("C++");
list.add("Python");
list.add("Big Data");
list.add("Machine Learning");
HBox hbox = new HBox(15);
//Setting the space between the nodes of a HBox pane
hbox.setPadding(new Insets(75, 150, 50, 60));
hbox.getChildren().addAll(label, combo);
//Creating a scene object
Scene scene = new Scene(new Group(hbox), 595, 280, Color.BEIGE);
stage.setTitle("Combo Box");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Output

ChoiceBox
A choice box holds a small set of multiple choices and, allows you to select only one of them.
This will have two states showing and not showing. When showing, you can see the list of

14
choices in a choice box and while not showing, it displays the current choice. By default, no
option is selected in a choice box.
In JavaFX a choice box is represented by the class javafx.scene.control.ChoiceBox<T>. You
can create a choice box by instantiating this class.
This class has a property named items, it is of the type ObservableList<T> and it holds the
list of choices to display in the choice box. You can retrieve this list using
the getItems() method.
After instantiating the ChoiceBox class, you need to get the observable list and add all the
required choices to it using the add() or addAll() method.
Example
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class ChoiceBoxExample extends Application {
public void start(Stage stage) {
//Creating a choice box
ChoiceBox<String> choiceBox = new ChoiceBox<String>();
choiceBox.setValue("English");
//Retrieving the observable list
ObservableList<String> list = choiceBox.getItems();
//Adding items to the list
list.add("English");
list.add("Hindi");
list.add("Telugu");
list.add("Tamil");
//Setting the position of the choice box
choiceBox.setTranslateX(200);
choiceBox.setTranslateY(15);
//Setting the label
Label label = new Label("Select Display Language:");
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
label.setTranslateX(20);
label.setTranslateY(20);
//Adding the choice box to the group
Group root = new Group(choiceBox, label);
//Setting the stage
Scene scene = new Scene(root, 595, 170, Color.BEIGE);
stage.setTitle("Choice Box Example");
stage.setScene(scene);
stage.show();
}

15
public static void main(String args[]){
launch(args);
}
}
Output

Text Control
Just like various shapes, you can also create a text node in JavaFX. The text node is represented
by the class named Text, which belongs to the package javafx.scene.text.
This class contains several properties to create text in JavaFX and modify its appearance. This
class also inherits the Shape class which belongs to the package javafx.scene.shape.
Therefore, in addition to the properties of the text like font, alignment, line spacing, text, etc.
It also inherits the basic shape node properties such as strokeFill, stroke, strokeWidth,
strokeType, etc.
Creating a Text Node
Since the class Text of the package javafx.scene.text represents the text node in JavaFX, you
can create a text by instantiating this class as follows −
Text text = new Text();
The class Text contains a property named text of string type, which represents the text that is
to be created.
After instantiating the Text class, you need to set value to this property using
the setText() method as shown below.
String text = "Hello how are you"
Text.setText(text);
You can also set the position (origin) of the text by specifying the values to the properties x
and y using their respective setter methods namely setX() and setY() as shown in the following
code block −
text.setX(50);
text.setY(50);
Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class TextFieldTest extends Application
{
public static void main(String[] args) {
launch(args);
}

16
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label user_id=new Label("User ID");
Label password = new Label("Password");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button b = new Button("Submit");
GridPane root = new GridPane();
root.addRow(0, user_id, tf1);
root.addRow(1, password, tf2);
root.addRow(2, b);
Scene scene=new Scene(root,800,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Text Field Example");
primaryStage.show();
}
}

The following program is an example which displays a login page in JavaFX. Here, we are
using the controls label, text field, password field and button.
Save this code in a file with the name LoginPage.java.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class LoginPage extends Application {
@Override
public void start(Stage stage) {
//creating label email
Text text1 = new Text("Email");
//creating label password
Text text2 = new Text("Password");
//Creating Text Filed for email
TextField textField1 = new TextField();
//Creating Text Filed for password
PasswordField textField2 = new PasswordField();
//Creating Buttons
Button button1 = new Button("Submit");
Button button2 = new Button("Clear");
//Creating a Grid Pane
GridPane gridPane = new GridPane();

17
//Setting size for the pane
gridPane.setMinSize(400, 200);
//Setting the padding
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
gridPane.add(text1, 0, 0);
gridPane.add(textField1, 1, 0);
gridPane.add(text2, 0, 1);
gridPane.add(textField2, 1, 1);
gridPane.add(button1, 0, 2);
gridPane.add(button2, 1, 2);
//Styling nodes
button1.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
button2.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
text1.setStyle("-fx-font: normal bold 20px 'serif' ");
text2.setStyle("-fx-font: normal bold 20px 'serif' ");
gridPane.setStyle("-fx-background-color: BEIGE;");
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting title to the Stage
stage.setTitle("CSS 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);
}
}
On executing, the above program generates a JavaFX window as shown below.

The following program is an example of a registration form, which demonstrates controls in


JavaFX such as Date Picker, Radio Button, Toggle Button, Check Box, List View, Choice
List, etc.

18
Save this code in a file with the name Registration.java.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;
public class Registration extends Application {
@Override
public void start(Stage stage) {
//Label for name
Text nameLabel = new Text("Name");
//Text field for name
TextField nameText = new TextField();
//Label for date of birth
Text dobLabel = new Text("Date of birth");
//date picker to choose date
DatePicker datePicker = new DatePicker();
//Label for gender
Text genderLabel = new Text("gender");
//Toggle group of radio buttons
ToggleGroup groupGender = new ToggleGroup();
RadioButton maleRadio = new RadioButton("male");
maleRadio.setToggleGroup(groupGender);
RadioButton femaleRadio = new RadioButton("female");
femaleRadio.setToggleGroup(groupGender);
//Label for reservation
Text reservationLabel = new Text("Reservation");
//Toggle button for reservation
ToggleButton Reservation = new ToggleButton();
ToggleButton yes = new ToggleButton("Yes");
ToggleButton no = new ToggleButton("No");
ToggleGroup groupReservation = new ToggleGroup();
yes.setToggleGroup(groupReservation);
no.setToggleGroup(groupReservation);
//Label for technologies known
Text technologiesLabel = new Text("Technologies Known");

19
//check box for education
CheckBox javaCheckBox = new CheckBox("Java");
javaCheckBox.setIndeterminate(false);
//check box for education
CheckBox dotnetCheckBox = new CheckBox("DotNet");
javaCheckBox.setIndeterminate(false);
//Label for education
Text educationLabel = new Text("Educational qualification");
//list View for educational qualification
ObservableList<String> names = FXCollections.observableArrayList(
"Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> educationListView = new ListView<String>(names);
//Label for location
Text locationLabel = new Text("location");
//Choice box for location
ChoiceBox locationchoiceBox = new ChoiceBox();
locationchoiceBox.getItems().addAll
("Hyderabad", "Chennai", "Delhi", "Mumbai", "Vishakhapatnam");
//Label for register
Button buttonRegister = new Button("Register");
//Creating a Grid Pane
GridPane gridPane = new GridPane();
//Setting size for the pane
gridPane.setMinSize(500, 500);
//Setting the padding
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
gridPane.add(nameLabel, 0, 0);
gridPane.add(nameText, 1, 0);
gridPane.add(dobLabel, 0, 1);
gridPane.add(datePicker, 1, 1);
gridPane.add(genderLabel, 0, 2);
gridPane.add(maleRadio, 1, 2);
gridPane.add(femaleRadio, 2, 2);
gridPane.add(reservationLabel, 0, 3);
gridPane.add(yes, 1, 3);
gridPane.add(no, 2, 3);
gridPane.add(technologiesLabel, 0, 4);
gridPane.add(javaCheckBox, 1, 4);
gridPane.add(dotnetCheckBox, 2, 4);
gridPane.add(educationLabel, 0, 5);
gridPane.add(educationListView, 1, 5);
gridPane.add(locationLabel, 0, 6);
gridPane.add(locationchoiceBox, 1, 6);
gridPane.add(buttonRegister, 2, 8);

20
//Styling nodes
buttonRegister.setStyle("-fx-background-color: darkslateblue; -fx-textfill: white;");
nameLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
dobLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
genderLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
reservationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
technologiesLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
educationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
locationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
//Setting the back ground color
gridPane.setStyle("-fx-background-color: BEIGE;");
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting title to the Stage
stage.setTitle("Registration Form");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
On executing, the above program generates a JavaFX window as shown below.

Scroll panes
Scroll panes provide a scrollable view of UI elements.

21
We use scrollable panel when we need to show a large content with limited space. The
scrollable pane has a viewport which will show a portion of the content and it provides a
scroll bar when necessary.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
//from w ww . j a va 2 s . c o m
public class Main extends Application {
@Override
public void start(Stage stage) {
stage.setWidth(500);
stage.setHeight(500);
Scene scene = new Scene(new Group());
VBox root = new VBox();
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(browser);
webEngine.loadContent("<b>asdf</b>");
root.getChildren().addAll(scrollPane);
scene.setRoot(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The code above generates the following result.

Layouts
After constructing all the required nodes in a scene, we will generally arrange them in order.
This arrangement of the components within the container is called the Layout of the container.
We can also say that we followed a layout as it includes placing all the components at a
particular position within the container.
JavaFX provides several predefined layouts such as HBox, VBox, Border Pane, Stack Pane,
Text Flow, Anchor Pane, Title Pane, Grid Pane, Flow Panel, etc.

22
Each of the above mentioned layout is represented by a class and all these classes belongs to
the package javafx.layout. The class named Pane is the base class of all the layouts in JavaFX.
Creating a Layout
To create a layout, you need to −
 Create node.
 Instantiate the respective class of the required layout.
 Set the properties of the layout.
 Add all the created nodes to the layout.
Creating Nodes
First of all, create the required nodes of the JavaFX application by instantiating their respective
classes.
For example, if you want to have a text field and two buttons namely, play and stop in a HBox
layout - you will have to initially create those nodes as shown in the following code block −
//Creating a text field
TextField textField = new TextField();
//Creating the play button
Button playButton = new Button("Play");
//Creating the stop button
Button stopButton = new Button("stop");
Instantiating the Respective Class
After creating the nodes (and completing all the operations on them), instantiate the class of
the required layout.
For Example, if you want to create a Hbox layout, you need to instantiate this class as follows.
HBox hbox = new HBox();
Setting the Properties of the Layout
After instantiating the class, you need to set the properties of the layout using their respective
setter methods.
For example − If you want to set space between the created nodes in the HBox layout, then you
need to set value to the property named spacing. This can be done by using the setter
method setSpacing() as shown below −
hbox.setSpacing(10);
Adding the Shape Object to the Group
Finally, you need to add the object of the shape to the group by passing it as a parameter of the
constructor as shown below.
//Creating a Group object
Group root = new Group(line);
Layout Panes
Following are the various Layout panes (classes) provided by JavaFX. These classes exist in
the package javafx.scene.layout.
S.No Shape & Description

1 HBox
The HBox layout arranges all the nodes in our application in a single horizontal row.
The class named HBox of the package javafx.scene.layout represents the text horizontal
box layout.

2 VBox
The VBox layout arranges all the nodes in our application in a single vertical column.

23
The class named VBox of the package javafx.scene.layout represents the text Vertical box
layout.

3 BorderPane
The Border Pane layout arranges the nodes in our application in top, left, right, bottom and
center positions.
The class named BorderPane of the package javafx.scene.layout represents the border
pane layout.

4 StackPane
The stack pane layout arranges the nodes in our application on top of another just like in a
stack. The node added first is placed at the bottom of the stack and the next node is placed
on top of it.
The class named StackPane of the package javafx.scene.layout represents the stack pane
layout.

5 TextFlow
The Text Flow layout arranges multiple text nodes in a single flow.
The class named TextFlow of the package javafx.scene.layout represents the text flow
layout.

6 AnchorPane
The Anchor pane layout anchors the nodes in our application at a particular distance from
the pane.
The class named AnchorPane of the package javafx.scene.layout represents the Anchor
Pane layout.

7 TilePane
The Tile Pane layout adds all the nodes of our application in the form of uniformly sized
tiles.
The class named TilePane of the package javafx.scene.layout represents the TilePane
layout.

8 GridPane
The Grid Pane layout arranges the nodes in our application as a grid of rows and columns.
This layout comes handy while creating forms using JavaFX.
The class named GridPane of the package javafx.scene.layout represents the GridPane
layout.

9 FlowPane
The flow pane layout wraps all the nodes in a flow. A horizontal flow pane wraps the
elements of the pane at its height, while a vertical flow pane wraps the elements at its width.
The class named FlowPane of the package javafx.scene.layout represents the Flow Pane
layout.

FlowPane
If we use flow pane in our application, all the nodes are wrapped in a flow. A horizontal flow
pane wraps the elements of the pane at its height, while a vertical flow pane wraps the elements
at its width.

24
The class named FlowPane of the package javafx.scene.layout represents the Flow Pane.
This class contains 7 properties, which includes −
 alignment − This property represents the alignment of the contents of the Flow pane.
You can set this property using the setter method setAllignment().
 columnHalignment − This property represents the horizontal alignments of nodes in a
vertical flow pane.
 rowValignment − This property represents the vertical alignment of nodes in a
horizontal flow pane.
 Hgap − This property is of double type and it represents the horizontal gap between the
rows/columns of a flow pane.
 Orientation − This property represents the orientation of a flow pane.
 Vgap − This property is of double type and it represents the vertical gap between the
rows/columns of a flow pane.
Example
The following program is an example of the FlowPane layout. In this, we are inserting four
button in the horizontal flow pane.
Save this code in a file with the name FlowPaneExample.java.
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.scene.shape.Sphere;
import javafx.stage.Stage;
public class FlowPaneExample extends Application {
@Override
public void start(Stage stage) {
//Creating button1
Button button1 = new Button("Button1");
//Creating button2
Button button2 = new Button("Button2");
//Creating button3
Button button3 = new Button("Button3");
//Creating button4
Button button4 = new Button("Button4");
//Creating a Flow Pane
FlowPane flowPane = new FlowPane();
//Setting the horizontal gap between the nodes
flowPane.setHgap(25);
//Setting the margin of the pane
flowPane.setMargin(button1, new Insets(20, 0, 20, 20));
//Retrieving the observable list of the flow Pane
ObservableList list = flowPane.getChildren();
//Adding all the nodes to the flow pane
list.addAll(button1, button2, button3, button4);
//Creating a scene object
Scene scene = new Scene(flowPane);
//Setting title to the Stage
stage.setTitle("Flow Pane Example");
//Adding scene to the stage

25
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 FlowPaneExample.java
java FlowPaneExample
On executing, the above program generates a JavaFX window as shown below.

HBox and VBox


The HBox and VBox layouts are very similar, both lay out their children in a single line.
Common characteristics
If an HBox or a VBox have a border and/or padding set, then the contents will be layed out
within those insets.
They lay out each managed child regardless of the child's visible property value; unmanaged
children are ignored.
The alignment of the content is controlled by the alignment property, which defaults
to Pos.TOP_LEFT .
HBox
HBox lays out its children in a single horizontal row from left to right.
HBox will resize children (if resizable) to their preferred widths and uses its fillHeight
property to determine whether to resize their heights to fill its own height or keep their heights
to their preferred (fillHeight defaults to true).
Creating a HBox
// HBox example
HBox row = new HBox();
Label first = new Label("First");
Label second = new Label("Second");
row.getChildren().addAll(first, second);

26
VBox
VBox lays out its children in a single vertical column from top to bottom.
VBox will resize children (if resizable) to their preferred heights and uses its fillWidth
property to determine whether to resize their widths to fill its own width or keep their widths
to their preferred (fillWidth defaults to true).
Creating a VBox
// VBox example
VBox column = new VBox();
Label upper = new Label("Upper");
Label lower = new Label("Lower");
column.getChildren().addAll(upper, lower);

Set Padding and Spacing for HBox


import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
/*w ww.ja v a 2s. c o m*/
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("HBox Test");
// HBox
HBox hb = new HBox();
hb.setPadding(new Insets(15, 12, 15, 12));
hb.setSpacing(10);
// Buttons
Button btn1 = new Button();
btn1.setText("Button1");
hb.getChildren().add(btn1);

Button btn2 = new Button();

27
btn2.setText("Button2");
hb.getChildren().add(btn2);
Button btn3 = new Button();
btn3.setText("Button3");
hb.getChildren().add(btn3);
Button btn4 = new Button();
btn4.setText("Button4");
hb.getChildren().add(btn4);
// Adding HBox to the scene
Scene scene = new Scene(hb);
primaryStage.setScene(scene);
primaryStage.show();
}
}
The code above generates the following result.

VBox
Set Padding and Spacing
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
/*from ww w .ja v a 2s .c o m*/
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("VBox Test");
// VBox
VBox vb = new VBox();
vb.setPadding(new Insets(10, 50, 50, 50));
vb.setSpacing(10);

Label lbl = new Label("VBox");


lbl.setFont(Font.font("Amble CN", FontWeight.BOLD, 24));

28
vb.getChildren().add(lbl);
// Buttons
Button btn1 = new Button();
btn1.setText("Button1");
vb.getChildren().add(btn1);
Button btn2 = new Button();
btn2.setText("Button2");
vb.getChildren().add(btn2);
Button btn3 = new Button();
btn3.setText("Button3");
vb.getChildren().add(btn3);
Button btn4 = new Button();
btn4.setText("Button4");
vb.getChildren().add(btn4);
// Adding VBox to the scene
Scene scene = new Scene(vb);
primaryStage.setScene(scene);
primaryStage.show();
}
}
The code above generates the following result.

BorderPane
If we use the BorderPane, the nodes are arranged in the Top, Left, Right, Bottom and Center
positions.
The class named BorderPane of the package javafx.scene.layout represents the BorderPane.
This class contains five properties, which include −
 bottom − This property is of Node type and it represents the node placed at the bottom
of the BorderPane. You can set value to this property using the setter
method setBottom().
 center − This property is of Node type and it represents the node placed at the center of
the BorderPane. You can set value to this property using the setter method setCenter().
 left − This property is of Node type and it represents the node placed at the left of the
BorderPane. You can set value to this property using the setter method setLeft().
 right − This property is of Node type and it represents the node placed at the right of
the BorderPane. You can set value to this property using the setter method setRight().
 top − This property is of Node type and it represents the node placed at the top of the
BorderPane. You can set value to this property using the setter method setTop().

29
In addition to these, this class also provides the following method −
 setAlignment() − This method is used to set the alignment of the nodes belonging to
this pane. This method accepts a node and a priority value.
Example
The following program is an example of the BorderPane layout. In this, we are inserting a five
text fields in the Top, Bottom, Right, Left and Center positions.
Save this code in a file with the name BorderPaneExample.java.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BorderPaneExample extends Application {
@Override
public void start(Stage stage) {
//Instantiating the BorderPane class
BorderPane bPane = new BorderPane();
//Setting the top, bottom, center, right and left nodes to the pane
bPane.setTop(new TextField("Top"));
bPane.setBottom(new TextField("Bottom"));
bPane.setLeft(new TextField("Left"));
bPane.setRight(new TextField("Right"));
bPane.setCenter(new TextField("Center"));
//Creating a scene object
Scene scene = new Scene(bPane);
//Setting title to the Stage
stage.setTitle("BorderPane 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 BorderPaneExample.java
java BorderPaneExample
On executing, the above program generates a JavaFX window as shown below.

30
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.StackPane class. 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 the setAlignment(Node child,
StackPane's width and height 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);

31
}

}
Output:

GridPane
If we use Grid Pane in our application, all the nodes that are added to it are arranged in a way
that they form a grid of rows and columns. This layout comes handy while creating forms using
JavaFX.
The class named GridPane of the package javafx.scene.layout represents the GridPane. This
class provides eleven properties, which are −
 alignment − This property represents the alignment of the pane and you can set value
of this property using the setAlignment() method.
 hgap − This property is of the type double and it represents the horizontal gap between
columns.
 vgap − This property is of the type double and it represents the vertical gap between
rows.
 gridLinesVisible − This property is of Boolean type. On true, the lines of the pane are
set to be visible.
Following are the cell positions in the grid pane of JavaFX −
(0, 0) (1, 0) (2, 0)
(2, 1) (1, 1) (0, 1)
(2, 2) (1, 2) (0, 2)
Example
The following program is an example of the grid pane layout. In this, we are creating a form
using a Grid Pane.
Save this code in a file with the name GridPaneExample.java.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class GridPaneExample extends Application {
@Override
public void start(Stage stage) {

32
//creating label email
Text text1 = new Text("Email");
//creating label password
Text text2 = new Text("Password");
//Creating Text Filed for email
TextField textField1 = new TextField();
//Creating Text Filed for password
TextField textField2 = new TextField();
//Creating Buttons
Button button1 = new Button("Submit");
Button button2 = new Button("Clear");
//Creating a Grid Pane
GridPane gridPane = new GridPane();
//Setting size for the pane
gridPane.setMinSize(400, 200);
//Setting the padding
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
gridPane.add(text1, 0, 0);
gridPane.add(textField1, 1, 0);
gridPane.add(text2, 0, 1);
gridPane.add(textField2, 1, 1);
gridPane.add(button1, 0, 2);
gridPane.add(button2, 1, 2);
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting title to the Stage
stage.setTitle("Grid Pane 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 GridPaneExample.java
java GridPaneExample
On executing, the above program generates a JavaFX window as shown below.

33
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 are the example of background events.
Events in JavaFX
JavaFX provides support to handle a wide varieties 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 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.

34
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.
 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);

35
//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);
}
}

36
Menus
JavaFX provides a Menu class to implement menus. Menu is the main component of a
any application. In JavaFX, javafx.scene.control.Menu class provides all the methods
to deal with menus. This class needs to be instantiated to create a Menu.
The following sample of code shows the implementation of JavaFX menu.
1. ManuBar menubar = new MenuBar(); //creating MenuBar
2. Menu MenuName = new Menu("Menu Name"); //creating Menu
3. MenuItem MenuItem1 = new MenuItem("Menu Item 1 Name"); //creating Menu Item
4. MenuName.getItems().add(MenuItem1); //adding Menu Item to the Menu
5. menubar.getMenus().add(MenuName); //adding Menu to the MenuBar

Java program to create a menu bar and add menu to it and also add menuitems to the
menu: This program creates a menubar indicated by the name mb. A menu will be created by
name m and 3 menuitems m1, m2, m3 will be added to the menu m and the menu m will be
added to menubar mb. The menubar will be created inside a scene, which in turn will be hosted
inside a stage. The function setTitle() is used to provide title to the stage. Then a VBox is
created, on which addChildren() method is called to attach the menubar inside the scene.
Finally, the show() method is called to display the final results.

37
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.scene.control.Alert.AlertType;
import java.time.LocalDate;
public class MenuBar_1 extends Application {
// launch the application
public void start(Stage s)
{
// set title for the stage
s.setTitle("creating MenuBar");
// create a menu
Menu m = new Menu("Menu");
// create menuitems
MenuItem m1 = new MenuItem("menu item 1");
MenuItem m2 = new MenuItem("menu item 2");
MenuItem m3 = new MenuItem("menu item 3");
// add menu items to menu
m.getItems().add(m1);
m.getItems().add(m2);
m.getItems().add(m3);
// create a menubar
MenuBar mb = new MenuBar();
// add menu to menubar
mb.getMenus().add(m);
// create a VBox
VBox vb = new VBox(mb);
// create a scene
Scene sc = new Scene(vb, 500, 300);
// set the scene
s.setScene(sc);
s.show();
}
public static void main(String args[])
{
// launch the application
launch(args);
}
}
Output :

38
Java program to create a menu bar and add a menu to it and also add menu items
to menu and also add an event listener to handle the events: This program creates a
menubar indicated by the name mb. A menu will be created by name m and 3
menuitems m1, m2, m3 will be added to the menu m and the menu m will be added to the
menubar mb. The menubar will be created inside a scene, which in turn will be hosted
inside a stage. The function setTitle() is used to provide title to the stage. Then a VBox is
created, on which addChildren() method is called to attach the menubar inside the scene.
Finally, the show() method is called to display the final results. A label will also be created
that will show which menuitem is selected. An action event will be created to process the
action when the menu item is clicked by the user.

// it and also add menuitems to menu and also add


// an event listener to handle the events
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.scene.control.Alert.AlertType;
import java.time.LocalDate;
public class MenuBar_2 extends Application {
// launch the application
public void start(Stage s)
{
// set title for the stage
s.setTitle("creating MenuBar");
// create a menu
Menu m = new Menu("Menu");
// create menuitems
MenuItem m1 = new MenuItem("menu item 1");
MenuItem m2 = new MenuItem("menu item 2");
MenuItem m3 = new MenuItem("menu item 3");
// add menu items to menu
m.getItems().add(m1);
m.getItems().add(m2);

39
m.getItems().add(m3);
// label to display events
Label l = new Label("\t\t\t\t"+ "no menu item selected");
// create events for menu items
// action event
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
l.setText("\t\t\t\t" + ((MenuItem)e.getSource()).getText() +" selected");
}
};
// add event
m1.setOnAction(event);
m2.setOnAction(event);
m3.setOnAction(event);
// create a menubar
MenuBar mb = new MenuBar();
// add menu to menubar
mb.getMenus().add(m);
// create a VBox
VBox vb = new VBox(mb, l);
// create a scene
Scene sc = new Scene(vb, 500, 300);
// set the scene
s.setScene(sc);
s.show();
}
public static void main(String args[])
{
// launch the application
launch(args);
}
}
Output

40

You might also like