1
Unit – 5: JAVAFX EVENT HANDLING, CONTROLS AND
COMPONENTS
Chapter
Topic Page No.
No.
Introduction to JavaFX 1
5.1 5.1.1: JavaFX Application Structure 2
5.1.2: Lifecycle of a JavaFX Application 4
JavaFX Events 5
5.2 5.2.1: Basics of JavaFX Events 5
5.2.2: Event Handling 6
Handling Key Events and Mouse Events 10
5.3 5.3.1: Handling Key Events 10
5.3.2: Handling Mouse Events 13
5.4 JavaFX UI Controls 16
Layouts – FlowPane – HBox and VBox – BorderPane –
5.5 24
StackPane – GridPane.
5.6 Menus – Basics – Menu – Menu bars – MenuItem. 32
2
UNIT V JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS
JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events.
Controls: Checkbox, ToggleButton – RadioButtons – ListView – ComboBox –
ChoiceBox – Text Controls – ScrollPane. Layouts – FlowPane – HBox and VBox –
BorderPane – StackPane – GridPane. Menus – Basics – Menu – Menu bars –
MenuItem.
5.1: Introduction to JavaFX
What is JavaFX?
JavaFX is a set of graphics and media packages that enable developers to design,
create, test, debug, and deploy desktop applications and Rich Internet
Applications (RIA) that operate consistently across diverse platforms. The
applications built in JavaFX can run on multiple platforms including Web, Mobile, and
Desktops.
Features of JavaFX:
Feature Description
It consists of many classes and interfaces that are written in
Java Library
Java.
FXML is the XML based Declarative markup language. The
FXML coding can be done in FXML to provide the more enhanced GUI
to the user.
Scene Builder generates FXML mark-up which can be ported to
Scene Builder
an IDE.
Web View uses WebKitHTML technology to embed web pages
Web view
into the Java Applications.
Built-in controls are not dependent on operating system. The UI
Built in UI controls
components are used to develop a full featured application.
JavaFX code can be embedded with the CSS to improve the style
CSS like styling
and view of the application.
The JavaFX applications can be embedded with swing code
Swing
using the Swing Node class. We can update the existing swing
interoperability
application with the powerful features of JavaFX.
Canvas API provides the methods for drawing directly in an area
Canvas API
of a JavaFX scene.
Rich Set of APIs JavaFX provides a rich set of API's to develop GUI applications.
Integrated Graphics It is provided to deal with 2D and 3D graphics.
Library
3
JavaFX graphics are based on Graphics rendered
Graphics Pipeline pipeline(prism). It offers smooth graphics which are hardware
accelerated.
High Performance The media pipeline supports the playback of web multimedia on
Media Engine a low latency. It is based on a Gstreamer Multimedia framework.
Self-contained Self-Contained application packages have all of the application
application resources and a private copy of Java and JavaFX Runtime.
deployment model
5.1.1 : JavaFX Application Structure:
A JavaFX application will have three major components namely
1) Stage
2) Scene and
3) Nodes
as shown in the following diagram.
Figure: JavaFX [Link] Structure Figure: Scene Graph and Nodes
1) Stage
Stage(a window) in a JavaFX application is similar to the Frame in a Swing
Application. It acts like a container for all the JavaFX objects.
Primary Stage is created internally by the platform. Other stages can further be
created by the application.
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 −
o Decorated
o Undecorated
o Transparent
o Unified
o Utility
4
We have to call the show() method to display the contents of a stage.
2) 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 [Link] represents the scene object. At an
instance, the scene object is added to only one stage.
3) 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.
A node is of three types −
o Root Node − The first Scene Graph is known as the Root node.
o Branch Node/Parent Node − the node with child nodes are known as
branch/parent nodes. The parent nodes will be of the following types −
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.
Region − It is the base class of all the JavaFX Node based UI Controls,
such as Chart, Pane and Control.
WebView − This node manages the web engine and displays its
contents.
o Leaf Node − The node without child nodes is known as the leaf node.
5.1.2: Lifecycle of a JavaFX Application:
The JavaFX Application class has three life cycle methods, which are –
1) launch() - to launch JavaFX application.
2) init() − An empty method which can be overridden, but you
cannot create a stage or scene in this method.
3) start() − The entry point method where the JavaFX graphics
code is to be written.
4) stop() − An empty method which can be overridden, here we
can write the logic to stop the application.
5
General Rules for writing JavaFX Application:
A JavaFX Application must extend [Link].
The main() method should call [Link]()
The start() method is the main entry point for all JavaFX applications
Start() is called when a Stage is connected to the Operating System’s
window
The content of the scene is represented as a hierarchical scene graph of nodes:
Stage is the top-level JavaFX Container
Scene is the container for all content
5.2 JavaFX Events
5.2.1 : Basic of JavaFX Events:
A GUI based applications are mostly driven by Events. Events are the actions that the
user performs and the responses the application generates.
Example: Button clicks by user, key press on the application etc.
An event is a notification about a change. It encapsulates the state changes in the
event source. Registered event filters and event handlers within the application
receive the event and provide a response.
JavaFX provides support to handle events through the base class “Event” which is
available in the package [Link].
6
Examples of Events:
o Action Event — widely used to indicate things like when a button is pressed.
Class:- ActionEvent
Actions:- button pressed.
o Mouse Event — occurs when mouse is clicked
Class:- MouseEvent
Actions:- mouse clicked, mouse pressed, mouse released, mouse moved, mouse
entered target, mouse exited target.
o Drag Event — occurs when the mouse is dragged.
Class:- DragEvent
Actions:- drag entered, drag dropped, drag entered target, drag exited target,
drag over.
o Key Event — indicates that a keystroke has occurred.
Class:- KeyEvent
Actions:- Key pressed, key released and key typed.
o Window Event:
Class:- WindowEvent
Actions:- window hiding, window shown, window hidden, window showing.
o Scroll Event — indicates scrolling by mouse wheel, track pad, touch screen, etc...
o TouchEvent — indicates a touch screen action
5.2.2 : Event Handling:
Event handling is the mechanism that controls the event and decides what should
happen, if an event occurs. It has the code which is known as Event Handler that is
executed when an event occurs.
7
Event Handling in JavaFX is done by Event Filters and Event Handlers. They contain the
event handling logic to process a generated event.
Every event in JavaFX has three properties:
1. Event source
2. Event target
3. Event type
S.N Property Description
It denotes source of the event i.e. the origin which is responsible
1 Event Source
for generating the event.
It denotes the node on which the event is created. It remains
unaffected for the generated event. Event Target is the instance
2 Event Target
of any of the class that implements the java interface
“EventTarget”.
It is the type of the event that is being generated. It is basically
the instance of EventType class.
3 Event Type
Example: KeyEvent class contains KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED types.
Phases of Event Handling in JavaFX:
Whenever an event is generated, JavaFX undergoes the following phases:
1. Target Selection – Depends on the particular event type.
2. Route Construction – Specified by the event target.
3. Event Capturing – Event travels from the stage to the event target.
4. Event Bubbling – Event travel back from the target to the stage.
1. Target Selection:
The first step to process an event is the selection of the event target. Event target
is the node on which the event is created. Event target is selected based in the
Event Type.
8
For key events, the target is the node that has key focus.
The node where the mouse cursor is located is the target for mouse events.
2. Route Construction:
Usually, an event travels through the event dispatchers in order in the event
dispatch chain. An Event Dispatch Chain is created to determine the default route
of the event whenever an event is generated. It contains the path from the stage
to the node on which the event is generated.
3. Event Capturing:
In this phase, an event is dispatched by the root node and passed down in the
Event Dispatch Chain to the target node.
Event Handlers will not be invoked in this phase.
If any node in the chain has registered the event filter for the type of event that
occurred, then the filter on that node is called. When the filter completes, the
event is moved down to the next node in the Dispatch Chain. If no event filters
consumes the event, then the event target receives and processes the generated
event.
4. Event Bubbling:
In this phase, a event returns from the target node to the root node along the
event dispatch chain.
Events handlers will be invoked in this phase.
If any node in the chain has a handler for the generated event, that handler is
executes. When the handler completes, the event is bubbled up in the chain. If the
handler is not registered for a node, the event is returned to the bubbled up to
next node in the route. If no handler in the path consumed the event, the root
node consumes the event and completes the processing.
Three methods for Event Handling:
1. Convenience Methods:
setOnKeyPressed(eventHandler);
setOnMouseClicked(eventHandler);
2. Event Handler/Filter Registration Methods:
addEventHandler(eventType, eventHandler);
addEventFilter(eventType, eventFilter);
3. Event Dispatcher Property (lambda expression).
Event Filters:
Event Filters provides the way to handle the events generated by the Keyboard
Actions, Mouse Actions, Scroll Actions and many more event sources.
They process the events during Event Capturing Phase.
A node must register the required event filters to handle the generated event on that
node. handle() method contains the logic to execute when the event is triggered.
9
Adding Event-Filter to a node:
To register the event filter for a node, addEventFilter() method is used.
Syntax:
[Link] (<Event_Type>, new EventHandler<Event-Type>()
{
public void handle(Event-Type)
{
//Actual logic
});
Where,
First argument is the type of event that is generated.
Second argument is the filter to handle the event.
Removing Event-Filter:
We can remove an event filter on a node using removeEventFilter() method.
Syntax:
[Link](<Input-Event>, filter);
Event Handlers:
Event Filters provides the way to handle the events generated by the Keyboard
Actions, Mouse Actions, Scroll Actions and many more event sources.
They are used to handle the events during Event Bubbling Phase.
A node must register the event handlers to handle the generated event on that node.
handle() method contains the logic to execute when the event is triggered.
Adding Event-Handler to a node:
To register the event handler for a node, addEventHandler() method is used.
Syntax:
[Link] (<Event_Type>, new EventHandler<Event-Type>()
{
public void handle(<Event-Type> e)
{
//Handling Code
});
Where,
First argument is the type of event that is generated.
Second argument is the filter to handle the event.
Removing Event-Filter:
We can remove an event handler on a node using removeEventHandler() method.
10
Syntax:
[Link](<EventType>, handler);
A node can register for more than one Event Filters and Handlers.
The interface [Link] must be implemented by all the event filters and
event handlers.
5.3: Handling Key Events and Mouse Events
5.3.1 : HANDLING KEY EVENTS
Key Event − It 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.
Types of Key Event in Java
1. KEY_PRESSED – When a key on the keyboard is pressed, this event will be
triggered.
2. KEY_RELEASED – When the pressed key on the keyboard is released, this event
will be executed.
3. KEY_TYPED – This event will be triggered when a Unicode character is entered
Methods in the KeyEvent class to get the key details
KeyCode getCode() – This method returns the key information or the KeyCode
enum constant linked with the pressed or released key.
String getText() – This method returns a String description of the KeyCode linked
with the KEY_PRESSED and KEY_RELEASED events.
String getCharacter() – This method returns a string representing a character or a
sequence of characters connected with the KEY_TYPED event.
Example:
/* Program to handle KeyTyped and KeyPressed Events.
Whenever a key is pressed in TextFiled1, it will be displayed in TextFiled2.
Whenever BackSpace key is pressed in TextFiled1, last character in TextFiled2 will
be erased.
If you attempt to type a character in TextField2, alert box will be displaying */
import [Link];
import static [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
11
public class NewFXMain extends Application {
@Override
public void start(Stage primaryStage)
{
TextField tf1=new TextField();
TextField tf2=new TextField();
Label l1=new Label("Text Pressed : ");
EventHandler<KeyEvent> handler1=new EventHandler<KeyEvent>() {
String str="",str1="";
int d;
public void handle(KeyEvent event)
{
if([Link]()== KeyCode.BACK_SPACE)
{
str=[Link](0,[Link]()-1);
[Link](str);
}
else
{
str+=[Link]();
[Link](str);
}
}
};
EventHandler<KeyEvent> handler2=new EventHandler<KeyEvent>(){
public void handle(KeyEvent event)
{
Alert a=new Alert([Link]);
[Link]("Sorry! Dont Type Anything Here!!");
[Link]();
}
};
[Link](handler1);
[Link](handler2);
GridPane root = new GridPane();
[Link](1,tf1);
[Link](2,l1);
[Link](3,tf2);
Scene scene = new Scene(root, 300, 250);
[Link]("KeyEvent-Demo");
[Link](scene);
[Link]();
}
12
public static void main(String[] args) {
launch(args);
}
}
5.3.2 : HANDLING MOUSE EVENTS
JavaFX Mouse Events are used to handle mouse events. The MouseEvents works when
you Clicked, Dragged, or Pressed and etc. An object of the MouseEvent class represents
a mouse events.
Types of Mouse Events in JavaFX
ANY – This mouse event type is known as the supertype of all mouse event types. If
you want your node to receive all types of events. This event type would be used for
your handlers.
MOUSE_PRESSED – When you press a mouse button, this event is triggered. The
MouseButton enum defines three constants that represent a mouse button: NONE,
PRIMARY, and SECONDARY. The MouseEvent class’s getButton() method returns the
mouse button that is responsible for the event.
13
MOUSE_RELEASED – The event is triggered if you pressed and released a mouse
button in the same node.
MOUSE_CLICKED – This event will occur when you pressed and released a node.
MOUSE_MOVED – Simply move your mouse without pressing any mouse buttons to
generate this type of mouse event.
MOUSE_ENTERED – This event occurs when the mouse or cursor enters the target
node.
MOUSE_EXITED – This event occurs when the mouse or cursor leaves or moved
outside the target node.
MOUSE_DRAGGED – This event occurs when you move the mouse with a pressed
mouse button to a target node.
Example:
import [Link];
import [Link].*;
import [Link].*;
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
public class MouseEvents
extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
Label status=new Label();
[Link]("Mouse Event");
[Link]("Hello");
[Link](new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
[Link]("Mouse pressed");
}
});
[Link](e-> {
[Link]("Mouse Entered");
});
[Link](e-> {
[Link]("Mouse Exited");});
14
[Link](e-> {
[Link]("Mouse Released");
});
BorderPane bp = new BorderPane();
[Link](btn);
[Link](status);
Scene scene = new Scene(bp, 300, 250);
[Link](e-> {
[Link]("Mouse Dragged");
});
[Link]("MouseEvent-Demo");
[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}
OUTPUT
15
5.4: JavaFX UI Controls
Every user interface considers the following three main aspects −
1. UI elements − These are the core visual elements which the user eventually sees
and interacts with.
2. Layouts − They define how UI elements should be organized on the screen.
3. Behavior − These are events which occur when the user interacts with UI
elements.
16
JavaFX provides several classes in the package [Link].
17
Figure: JavaFX UI Controls
18
S. No. UI Control Description Constructors
Component that is used to define a new Label()
1. Label simple text on the screen. It is an not new Label(String S, Node n)
editable text control. new Label(String s)
Used to get the input from the user in
2. TextField the form of text. Allows to enter a New TextField()
limited quantity of text.
Used to get the kind of information
from the user which contains various new CheckBox()
3. CheckBox
choices. User marked the checkbox new CheckBox(String s)
either on (true) or off(false).
Used to provide various options to the
user. The user can only choose one new RadioButton()
4. RadioButton
option among all. A radio button is new RadioButton(String s)
either selected or deselected.
Component that controls the function new Button()
5. Button
of the application. new Button(String s)
new ComboBox
Shows a list of items out of which user
6. ComboBox new
can select at most one item
ComboBox(ObservableList i)
Shows a set of items and allows the
user to select a single choice and it will
new ChoiceBox
show the currently selected item on
7. ChoiceBox new
the top. ChoiceBox by default has no
ChoiceBox(ObservableList i)
selected item unless otherwise
selected.
Enables users to choose one or more
8. ListView options from a predefined list of new ListView();
choices.
It provides a scrollable view of UI
Elements. It is a container that has two
scrollbars around the component it
contains if the component is larger
9. ScrollPane new ScrollPane();
than the visible area of the ScrollPane.
The scrollbars enable the user to scroll
around the component shown inside
the ScrollPane
Special control having the ability to be new ToggleButton
selected. Basically, ToggleButton is newToggleButton(String txt)
rendered similarly to a Button but new ToggleButton(String txt,
these two are the different types of Node graphic)
10. ToggleButton Controls. A Button is a “command”
button that invokes a function when
clicked. But a ToggleButton is a control
with a Boolean indicating whether it is
selected.
19
Example : JavaFX program for Simple Registration form using UI Controls:
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class JavaFXControlDemo extends Application {
@Override
public void start(Stage stage)
{
//Label for name
Text nameLabel = new Text("Name");
//Text field for name
TextField nameText = new TextField();
20
//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");
[Link](groupGender);
RadioButton femaleRadio = new RadioButton("female");
[Link](groupGender);
//Label for reservation
Text reservationLabel = new Text("Reservation");
//Toggle button for reservation
ToggleButton yes = new ToggleButton("Yes");
ToggleButton no = new ToggleButton("No");
ToggleGroup groupReservation = new ToggleGroup();
[Link](groupReservation);
[Link](groupReservation);
//Label for technologies known
Text technologiesLabel = new Text("Technologies Known");
//check box for education
CheckBox javaCheckBox = new CheckBox("Java");
[Link](false);
//check box for education
CheckBox dotnetCheckBox = new CheckBox("DotNet");
[Link](false);
//Label for education
Text educationLabel = new Text("Educational qualification");
//list View for educational qualification
ObservableList<String> names = [Link](
"B.E","M.E","BBA","MCA", "MBA", "Vocational", "[Link]", "Mphil",
"Phd");
ListView<String> educationListView = new ListView<String>(names);
[Link](100, 100);
[Link]().setSelectionMode([Link]
LTIPLE);
21
Label interest=new Label("Area of Interest");
ComboBox AoI=new ComboBox();
[Link]().addAll("Android App. Dev.", "IoS App. Dev.", "FUll Stack
Dev.", "Azure FrmWork", "AWS", "Web Dev.", "Ui/Ux Design");
[Link](3);
//Label for location
Text locationLabel = new Text("location");
//Choice box for location
ChoiceBox locationchoiceBox = new ChoiceBox();
[Link]().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
[Link](500, 500);
//Setting the padding
[Link](new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
[Link](5);
[Link](5);
//Setting the Grid alignment
[Link]([Link]);
//Arranging all the nodes in the grid
[Link](nameLabel, 0, 0);
[Link](nameText, 1, 0);
[Link](dobLabel, 0, 1);
[Link](datePicker, 1, 1);
[Link](genderLabel, 0, 2);
[Link](maleRadio, 1, 2);
[Link](femaleRadio, 2, 2);
[Link](reservationLabel, 0, 3);
[Link](yes, 1, 3);
[Link](no, 2, 3);
[Link](technologiesLabel, 0, 4);
[Link](javaCheckBox, 1, 4);
[Link](dotnetCheckBox, 2, 4);
22
[Link](educationLabel, 0, 5);
[Link](educationListView, 1, 5);
[Link](interest,0,6);
[Link](AoI,1,6);
[Link](locationLabel, 0, 7);
[Link](locationchoiceBox, 1, 7);
[Link](buttonRegister, 2, 8);
Scene scene = new Scene(gridPane);
//Setting title to the Stage
[Link]("Registration Form");
//Adding scene to the stage
[Link](scene);
//Displaying the contents of the stage
[Link]();
}
public static void main(String args[])
{
launch(args);
}
}
OUTPUT:
23
5.5: Layouts – FlowPane – HBox and VBox – BorderPane – StackPane – GridPane.
In JavaFX, Layout defines the way in which the components are to be seen on the stage. It
basically organizes the scene-graph nodes.
Layout Panes: Layout panes are containers which are used for flexible and dynamic
arrangements of UI controls within a scene graph of a JavaFX application.
Package used: [Link] package
JavaFX provides various built-in Layouts that are
5. FlowPane
1. Pane
6. GridPane
2. VBox
7. StackPane.
3. HBox
4. BorderPane
JavaFX provides many types of panes for
organizing nodes in a container:
24
Class Description Representation
Base class for layout panes.
It containes the getChildren()
Pane
method for returning a list of
nodes in the pane.
Places the nodes in a single
VBox
column
Places the nodes in a single
HBox
row
Places the nodes in the top,
BorderPane right, bottom, left and center
regions
Places the nodes row-by-row
FlowPane horizontally or column-by-
column vertically
25
Places the nodes in the cells
GridPane in a two-dimensional
grid(like matrix)
Places the nodes on top of
StackPane each other in the center of
the pane
Methods and Properties of different layouts:
Layout Constructors Methods/Properties
1. VBox() : creates layout with 0 spacing Property Description
2. Vbox(Double spacing) : creates layout with a Alignment
This property is for the align
spacing value of double type the nodes.
3. Vbox(Double spacing, Node? children) : This property is of the boole
The Widtht of resizeable no
VBox creates a layout with the specified spacing FillWidth
be made equal to the Widt
among the specified child nodes VBox by setting this property
4. Vbox(Node? children) : creates a layout This property is to set some
with the specified nodes having 0 spacing Spacing
among the nodes of VBox.
among them
Property Description
This represents the alignme
Alignment
nodes.
1. new HBox() : create HBox layout with 0
This is a boolean property. I
spacing this property to true the heig
HBox fillHeight
2. new Hbox(Double spacing) : create HBox nodes will become equal
layout with a spacing value height of the HBox.
This represents the space
spacing the nodes in the HBox. It is o
type.
Type Property Setter Methods
1. BorderPane() :- create the empty layout Node Bottom setBottom()
2. BorderPane(Node Center):- create the
Node Centre setCentre()
layout with the center node
BorderPane
3. BorderPane(Node Center, Node top, Node Node Left setLeft()
right, Node bottom, Node left) :- create
Node Right setRight()
the layout with all the nodes
Node Top setTop()
Property Description
The overall alignmen
alignment
the flowpane's conten
26
The horizontal align
columnHalignme
of nodes within
1. FlowPane() nt
columns.
2. FlowPane(Double Hgap, Double Vgap) hgap
Horizontal gap betw
3. FlowPane(Double Hgap, Double Vgap, Node? the columns.
Orientation of
children) orientation
flowpane
FlowPane 4. FlowPane(Node... Children) The preferred heigh
5. FlowPane(Orientation orientation) width where co
prefWrapLength should wrap in
6. FlowPane(Orientation orientation, double horizontal or ve
Hgap, Double Vgap) flowpane.
The vertical alignme
rowValignment
the nodes within the r
The vertical gap amon
vgap
rows
Property Description
Represents the align
alignment
the grid within the Gr
This property is inte
debugging. Lines
Public GridPane(): creates a gridpane with 0 displayed to sho
GridPane hgap/vgap. gridLinesVisible
gidpane's rows and
by setting this prop
true.
Horizontal gaps am
hgap
columns
vgap Vertical gaps among th
Property Description
1. StackPane()
2. StackPane(Node? Children) It represents the
StackPane alignment of c
alignment
within the Stac
width and height
Example: Program for Layouts, Menus and MenuBars, Event Handling
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
public class JavaFXApplication1 extends Application {
@Override//from ww w . ja v a2s . co m
public void start(Stage primaryStage) {
// Create the top section of the UI
Text tNumber1 = new Text("Number 1:");
27
Text tNumber2 = new Text("Number 2:");
Text tResult = new Text("Result:");
TextField tfNumber1 = new TextField();
TextField tfNumber2 = new TextField();
TextField tfResult = new TextField();
[Link](false);
Menu me=new Menu("Edit");
// create menuitems
MenuItem m1 = new MenuItem("Set Default Value");
MenuItem m2 = new MenuItem("Clear All values");
// add menu items to menu
[Link]().add(m1);
[Link]().add(m2);
Menu mc=new Menu("Bg_Color");
MenuItem c1 = new MenuItem("Red");
MenuItem c2 = new MenuItem("Green");
[Link]().addAll(c1,c2);
MenuBar mb = new MenuBar();
// add menu to menubar
[Link]().add(me);
[Link]().add(mc);
VBox vb=new VBox(mb);
[Link](e -> {
[Link]("10");
[Link]("20");
});
[Link](e ->{
[Link]("");
[Link]("");
[Link]("");
});
// Create the bottom section of the UI
Button btAdd = new Button("Add");
Button btSubtract = new Button("Subtract");
Button btMultiply = new Button("Multiply");
Button btDivide = new Button("Divide");
28
// Add top and bottom UI to HBox containers
GridPane calcTop = new GridPane();
[Link]([Link]);
[Link](new Insets(5));
[Link](tNumber1, 0, 0);
[Link](tfNumber1, 1, 0);
[Link](tNumber2, 0, 1);
[Link](tfNumber2, 1, 1);
[Link](tResult, 0, 2);
[Link](tfResult, 1, 2);
FlowPane calcBottom = new FlowPane();
[Link]([Link]);
[Link](new Insets(5));
[Link]().addAll(btAdd, btSubtract, btMultiply, btDivide);
// Add HBox containers to a BorderPane
BorderPane pane = new BorderPane();
[Link](vb);
[Link](calcTop);
[Link](calcBottom);
[Link](e -> {
[Link](new Background(new BackgroundFill([Link],null,null)));
});
[Link](e -> {
[Link](new Background(new
BackgroundFill([Link],null,null)));
});
// Register event handlers for buttons
[Link](e -> {
double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);
[Link]([Link](a + b));
});
[Link](e -> {
double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);
[Link]([Link](a - b));
});
29
[Link](e -> {
double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);
[Link]([Link](a * b));
});
[Link](e -> {
double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);
[Link](b == 0 ? "NaN" : [Link](a / b));
});
Scene scene = new Scene(pane);
[Link]("Simple Calculator");
[Link](scene);
[Link](false);
[Link]();
}
private static double getDoubleFromTextField(TextField t) {
return [Link]([Link]());
}
public static void main(String[] args) {
launch(args);
}
}
30
5.6: Menus – Basics – Menu – Menu bars – MenuItem.
5.6.1. JavaFX Menus, MenuItem and MenuBar:
Menu is a popup menu that contains several menu items that are displayed when
the user clicks a menu. The user can select a menu item after which the menu goes into
a hidden state.
MenuBar is usually placed at the top of the screen which contains several menus. JavaFX
MenuBar is typically an implementation of a menu bar.
Constructor of the MenuBar class are:
1. MenuBar(): creates a new empty menubar.
2. MenuBar(Menu... m): creates a new menubar with the given set of menu.
Constructor of the Menu class are:
1. Menu(): creates an empty menu
2. Menu(String s): creates a menu with a string as its label
3. Menu(String s, Node n):Constructs a Menu and sets the display text with the
specified text and sets the graphic Node to the given node.
4. Menu(String s, Node n, MenuItem... i):Constructs a Menu and sets the display text
with the specified text, the graphic Node to the given node, and inserts the given
items into the items list.
Commonly used methods:
Method Explanation
getItems() returns the items of the menu
hide() hide the menu
show() show the menu
getMenus() The menus to show within this MenuBar.
isUseSystemMenuBar() Gets the value of the property useSystemMenuBar
setUseSystemMenuBar(boolean
Sets the value of the property useSystemMenuBar.
v)
31
setOnHidden(EventHandler v) Sets the value of the property onHidden.
setOnHiding(EventHandler v) Sets the value of the property onHiding.
setOnShowing(EventHandler v) Sets the value of the property onShowing.
setOnShown(EventHandler v Sets the value of the property onShown.
JavaFX Menu
In the JavaFX application, in order to create a menu, menu items, and menu bar,
Menu, MenuItem, and MenuBar class is used. The menu allows us to choose
options among available choices in the application.
All methods needed for this purpose are present in the [Link]
class.
Example: Java program to create a menu bar and add menu to it and also add
menuitems to the menu
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MenuUI extends Application {
@Override
public void start(Stage primaryStage) throws Exception
{
Menu newmenu = new Menu("File");
Menu newmenu2 = new Menu("Edit");
MenuItem m1 = new MenuItem("Open");
MenuItem m2 = new MenuItem("Save");
MenuItem m3 = new MenuItem("Exit");
MenuItem m4 = new MenuItem("Cut");
MenuItem m5 = new MenuItem("Copy");
MenuItem m6 = new MenuItem("Paste");
[Link]().add(m1);
[Link]().add(m2);
[Link]().add(m3);
32
[Link]().add(m4);
[Link]().add(m5);
[Link]().add(m6);
MenuBar newmb = new MenuBar();
[Link]().add(newmenu);
[Link]().add(newmenu2);
VBox box = new VBox(newmb);
Scene scene = new Scene(box,400,200);
[Link](scene);
[Link]("JavaFX Menu Example");
[Link]();
}
public static void main(String[] args)
{
[Link](args);
}
}
Output: