Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

Unit - 5

JAVAFX EVENT
HANDLING, CONTROLS
AND COMPONENTS

Dr. S. Sathees Babu,


ssbabu@psnacet.edu.in
Outline

 Basics of JAVAFX

 JAVAFX Events and Controls

 Layouts

 Menus
GUI
 Graphical User Interface (GUI)
 provides user-friendly human interaction
Building Java GUIs require use of frameworks:
 AWT (1996)
 Swing (1998)
 Extremely powerful, many extensions available
 Complex to master, requires low-level handling
 Hard to create visually pleasing applications
 JavaFX (part of Java since JSE 8, 2014) includes:
 GUI components
 Event Programming
 Graphics
How do GUIs work?

Construct GUI Components

Render GUI

Check to see if any input

Respond to user input


JavaFX vs Swing and AWT
 Swing andAWT are replaced by the JavaFX platform for
developing rich Internet applications in JDK8 (2014)
 History:
 When Java was introduced (1996), the GUI classes were bundled in a library
known as theAbstractWindowsToolkit (AWT)
 AWT was prone to platform-specific bugs
 AWT was fine for developing simple graphical user interfaces, but not for develo
ping comprehensive GUI projects
 TheAWTuser-interface components were replaced by a more robust, versatile, a
nd flexible library known as Swing components (1997)
 Swing components are painted directly on canvases using Java code
 Swing components depend less on the target platform and use less of the native
GUI resource
 With the release of Java 8, Swing is replaced by a comple
tely new GUI platform: JavaFX
 JavaFX is a new framework for developing Java GUI programs. The JavaFXAPI
is an excellent example of how the object-oriented principle is applied.
JAVAFX Basics
 JavaFX is a set of Java graphics libraries for creating Java
GUI applications, just like Java AWT and Swing.
 JavaFX is a Java library and a GUI toolkit designed to develop
and facilitate Rich Internet applications, web applications, and
desktop applications.
 The most significant perk of using JavaFX is that the
applications written using this library can run on multiple
operating systems like Windows, Linux, iOS, Android, and
several platforms like Desktops, Web, Mobile Phones, TVs,
Tablets, etc.
 JavaFX to promote desktop and rich internet applications (RIA)
that can be accessed from the category of devices.
 Rich Internet Applications (RIA) are those web applications
that allow alike characteristics and expertise as that of desktop
applications. These applications contribute more satisfying
visual experience to the users when compared to the standard
web applications
JavaFX Key Features
1. From JavaFX 2.0, JavaFX is written in Java (no need to learn
a new language). Starting from JDK 8, JavaFX is part of JDK.
2. Support CSS for skinning.
3. Support FXML: a XML-based declarative language to define
the structure of the user interface separated from the application
code.
4. Swing interoperability: You can use Swing UI in JavaFX
application.
5. WebView: for embedding HTML contents.
6. 2D/3D Graphics
7. Media: audio (mp3, wav, aiff), video (flv) and image.
8. Provide a JavaScript engine.
JavaFX Key Features
1. JAVA Library
2. Platform Independent
3. FXML
4. Scene Builder
5. Hardware-accelerated Graphics Pipeline
6. WebView
7. Built-in UI controls
8. CSS Styling
9. Rich set of APIs
10. High-Performance media engine
JavaFX Architecture
 JavaFX library comprises a valuable collection of APIs, classes, and interfaces
that are more than sufficient to produce rich internet applications and GUI
applications with intense graphics that can run consistently over multiple
platforms.
JavaFX Architecture
 JavaFX API – The topmost layer of JavaFX architecture holds a
JavaFX public API that implements all the required classes that are
capable of producing fullfeatured JavaFX application with rich graphics
 javafx.animation: It includes classes that are used to combine
transition-based animations such as fill, fade, rotate, scale and translati
on, to the JavaFX nodes (collection of nodes makes a scene graph).
 javafx.css − It comprises classes that are used to append CSS–like
styling to the JavaFX GUI applications.
 javafx.geometry − It contains classes that are used to represent 2D
figures and execute methods on them.
 javafx.scene − This package of JavaFX API implements classes
and interfaces to establish the scene graph. In extension, it also
renders sub-packages such as canvas, chart, control, effect, image,
input, layout, media, paint, shape, text, transform, web, etc. These are
the diverse elements that sustain this precious API of JavaFX.
JavaFX Architecture
 javafx.application − This package includes a collection of classes that are
responsible for the life cycle of the JavaFX application.
 javafx.event − It includes classes and interfaces that are used to perform
and manage JavaFX events.
 javafx.stage − This package of JavaFX API accommodates the top-level
container classes used for the JavaFX application.
 Scene Graph – A Scene Graph is the starting point of the development of
any of the GUI Applications. In JavaFX, all the GUI Applications are made
using a Scene Graph only. The Scene Graph includes the primitives of the
rich internet applications that are known as nodes.
 The nodes are of three general types.
 These are as follows:
 Root Node – A root node is a node that does not have any node
as its parent.
 Leaf Node – A leaf node is a node that does not contain any node
as its children.
 Branch Node – A branch node is a node that contains a node as
its parent and also has a node as its children.
JavaFX Architecture
 Quantum Toolkit – Quantum Toolkit is used to connect prism and glass
windowing tool kits collectively and makes them prepared for the above layers
in the stack.
 Prism – The graphics of the JavaFX applications are based on the hardwar
e-accelerated graphics rendering pipeline, commonly known as Prism. The
Prism engine supports smooth JavaFX graphics that can be executed swiftly
when utilized with a backed graphics card or graphics processing unit (GPU).
In the situation where the system does not contain the graphic cards, then the
prism engine defaults to the software rendering stack. To interpret graphics, a
Prism practice −
 DirectX 9 on Windows XP and Vista.
 DirectX 11 on Windows 7.
 OpenGL on Mac and Linux, Embedded Systems.
 Glass Windowing Toolkit – Glass Windowing Toolkit or simply Glass is a
platform-dependent layer that assists in connecting the JavaFX platform to the
primary operating system (OS). Glass Windowing Toolkit is very useful as it pr
ovides services such as controlling the windows, events, timers, and surfaces
to the native operating system.
JavaFX Architecture
 WebView – JavaFX applications can also insert web pages. To embed
web pages, Web View of JavaFX uses a new HTML rendering engine
technology known as WebKitHTML. WebView is used to make it possible to
insert web pages within a JavaFX application. JavaScript appearing in Web
View can call Java APIs and vice-versa. This element promotes different
web technologies like HTML5, CSS, JavaScript, DOM, and SVG. Using web
view, we can execute the HTML content from the JavaFX application and
can also implement some CSS styles to the user interface (UI) part of the
application.
 Media Engine – Like the graphics pipeline, JavaFX also possesses a
media pipeline that advances stable internet multimedia playback at low
latency. This high-performance media engine or media pipeline is based on
a multimedia framework known as Gstreamer. By applying the Media engine
, the JavaFX application can support the playback of audio and video media
files. The package javafx.scene.media covers all the classes and
interfaces that can provide media functionalities to JavaFX applications.
Life Cycle of a JavaFX
Application
Life Cycle of a JavaFX
Application
 There are in total three life cycle methods of a JavaFX Application
class. These methods are –
 start() – The start() method is the entry point method of the
JavaFX application where all the graphics code of JavaFX is to
be written.
 init() – The init() method is an empty method that can be overri
-dden. In this method, the user cannot create a stage or a scene.
 stop() – The stop() method is an empty method that can also
be overridden, just like the init() method. In this method, the user
can write the code to halt the application.
 Other than these methods, the JavaFX application also implement
a static method known as launch().
 This launch() method is used to launch the JavaFX application. As
stated earlier, the launch() method is static, the user should call it
from a static method only. Generally, that static method, which calls
the launch() method, is the main() method only.
Life Cycle of a JavaFX
Application

 Whenever a user launches a JavaFX application, there are


few actions that are carried out in a particular manner only.
 The following is the order given in which a JavaFX application
is launched.
 Firstly, an instance of the application class is created.

 After that, the init() method is called.

 After the init() method, the start() method is called.

 After calling the start() method, the launcher waits for the
JavaFX application to end and then calls the stop() method.
Terminating the JavaFX
application
 As soon as the last window of the JavaFX application is clos
ed, the JavaFX application is stopped implicitly.
 The user can turn off this function by passing the Boolean
value “False” to the static method setImplicitExit().
 This method should always be called from a static context
only.
 The user can also stop a JavaFX application explicitly by
practicing any of the two methods,
 Platform.exit() or
 System.exit(int).
JavaFX Tooling
 JavaFX is supported in Netbeans.
See: http://netbeans.org/features/javafx/
Project management, composer, Language editor

 An Eclipse plug-in exists.


See: http://javafx.com/docs/gettingstarted/eclipse-plugin/

 JavaFX is supported on the command line.


See: http://www.sun.com/software/javafx
Install Java FX

TextPad tool also compile and run the JAVAFX code.

 The JavaFX code is compiled to Java byte code and runs on


the JVM.
J a v a F X 8 (J a v a F X 2.x)

 Redesigned from scratch


 The JavaFX 2.x/8.0 framework is entirely written in Java
 For visual layout, an XML file may also be used (called
FXML)
 Graphic appearance borrows from web-standard CSS style
sheets
 UI programming is based on easy to handle events and
bindings
 Oracle plans to deprecate Swing in favor of JavaFX 2
 Now called JavaFX 8 (after Java 8 – JDK 1.8)
Basic Structure of JavaFX
Basic Structure of JavaFX
 javafx.application.Application
 is the entry point for JavaFX applications
 JavaFX creates an application thread for running the application
start method, processing input events, and running animation
timelines.
 Override the start(Stage) method!
 javafx.stage.Stage
 is the top level JavaFX container.
 The primary Stage is constructed by the platform.
 javafx.scene.Scene class
 is the container for all content in a scene graph.
 javafx.scene.Node
 is the base class for scene graph nodes
Example – Single Stage
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;

public class MyFirstJavaFX extends Application {


// Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a button and place it in the scene
Button btOK = new Button("OK");
Scene scene = new Scene(btOK, 200, 250);
primaryStage.setTitle("MyJavaFX"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args) {
launch(args);
}
}
Example – Single Stage
Example – Multiple Stages
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
public class MultipleStageDemo extends Application {
// Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a scene and place a button in the scene
Scene scene = new Scene(new Button("OK"), 200, 250);
primaryStage.setTitle("MyJavaFX"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
Stage stage = new Stage(); // Create a new stage
stage.setTitle("Second Stage"); // Set the stage title
// Set a scene with a button in the stage
stage.setScene(new Scene(new Button("New Stage"), 100, 100));
stage.show(); // Display the stage
}
public static void main(String[] args) {
launch(args);
}}
Example – Multiple Stages
JavaFX - UI 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.
 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).
 Behavior − These are events which occur when the user interacts
with UI elements.
 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.
JavaFX - UI Controls
SN Control Description
1 Label Label is a component that is used to define a simple text on the screen.
Typically, a label is placed with the node, it describes.
2 Button Button is a component that controls the function of the application.
Button class is used to create a labelled button.
3 RadioButton The Radio Button is used to provide various options to the user. The
user can only choose one option among all. A radio button is either
selected or deselected.
4 CheckBox Check Box is used to get the kind of information from the user which
contains various choices. User marked the checkbox either on (true) or
off(false).
5 TextField Text Field is basically used to get the input from the user in the form of
text. javafx.scene.control.TextField represents TextField
6 PasswordField PasswordField is used to get the user's password. Whatever is typed in
the passwordfield is not shown on the screen to anyone.
7 HyperLink HyperLink are used to refer any of the webpage through your appication
. It is represented by the class javafx.scene.control.HyperLink
JavaFX - UI Controls
8 Slider Slider is used to provide a pane of options to the user in a graphical form
where the user needs to move a slider over the range of values to select
one of them.
9 ProgressBar Progress Bar is used to show the work progress to the user. It is represent
ed by the class javafx.scene.control.ProgressBar.
10 ProgressIndi Instead of showing the analogue progress to the user, it shows the digital
cator progress so that user may know the amount of work done in percentage.
11 ScrollBar JavaFX Scroll Bar is used to provide a scroll bar to the user so that the
user can scroll down the application pages
12 Menu JavaFX provides a Menu class to implement menus. Menu is the main
component of any application.
13 ToolTip JavaFX ToolTip is used to provide hint to the user about any component. It
is mainly used to provide hints about the text fields or password fields
being used in the application.
14 ColorPicker A ColorPicker provides a pane of controls designed to allow a user to
manipulate and select a color
15 ListView A ListView component presents the user with a scrolling list of text items
16 FileChooser A FileChooser control represents a dialog window from which the user can
select a file
JavaFX - UI Controls
 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
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;
JavaFX - UI Controls
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");
JavaFX - UI Controls
//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");
//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");
JavaFX - UI Controls
//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);
JavaFX - UI Controls
//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);
//Styling nodes
buttonRegister.setStyle(
"-fx-background-color: darkslateblue; -fx-textfill: white;");
JavaFX - UI Controls
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);
}}
JavaFX - UI Controls
JavaFX - UI Controls
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;  An example which
import javafx.scene.control.Button; displays a login
import javafx.scene.control.PasswordField; page in JavaFX
import javafx.scene.layout.GridPane; using the
import javafx.scene.text.Text; controls label, text
import javafx.scene.control.TextField; field, password
import javafx.stage.Stage; field and button
public class LoginPage extends Application {
public void start(Stage stage) {
//creating label email
Text text1 = new Text("Email");
//creating label password
Text text2 = new Text("Password");
JavaFX - UI Controls
//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();
//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);
JavaFX - UI Controls
//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);
}}
JavaFX - UI Controls
JavaFX - UI Controls
 In JavaFx, we can use hyper-links to refer the web pages. It is similar to
anchor links in HTML.
 javafx.scene.control.HyperLink class provides all the necessary methods
to deal with JavaFX hyper-links.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HyperLinkTest extends Application {
public static void main(String[] args) { launch(args); }
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Hyperlink hp = new Hyperlink("http://www.google.com");
StackPane root = new StackPane();
hp.setOnAction(e -> System.out.println("Link Clicked"));
root.getChildren().add(hp);
Scene scene=new Scene(root,400,300);
primaryStage.setScene(scene);
primaryStage.setTitle("Hyperlink Example");
primaryStage.show();
} }
JavaFX - UI Controls
JavaFX Layouts
 The JavaFX SDK provides layout panes that support
several different styles of layouts.
 Layouts are the top level container classes that define
the UI styles for scene graph objects.
 Layout can be seen as the parent node to all the other
nodes.
 All these classes belong to
javafx.scene.layout package.
 javafx.scene.layout.Pane
class is the base class for all
the built-in layout classes in
JavaFX.
JavaFX Layouts
Built-in layout classes in JavaFX
Class Description
BorderPane Organizes nodes in top, left, right, centre and the bottom of
the screen.
FlowPane Organizes the nodes in the horizontal rows according to the
available horizontal spaces. Wraps the nodes to the next line
if the horizontal space is less than the total width of the
nodes
GridPane Organizes the nodes in the form of rows and columns.

HBox Organizes the nodes in a single row.

Pane It is the base class for all the layout classes.

StackPane Organizes nodes in the form of a stack i.e. one onto another

VBox Organizes nodes in a vertical column.


JavaFX Layouts
Steps to create layout
 In order to create the layouts, we need to follow the following st
eps.
1. Creating Nodes, create the required nodes of the JavaFX a
pplication, for example,
//Creating a text field, TextField textField = new TextField();
//Creating the play button, Button playButton = new Button
("Play");
2. Instantiate the respective layout class, for example,
HBox root = new HBox();
3. Setting the properties for the layout, for example,
root.setSpacing(20);
4. Adding nodes to the layout object, for example,
root.getChildren().addAll(<NodeObjects>);
JavaFX FlowPane
 FlowPane layout pane organizes the nodes in a flow that
are wrapped at the flowpane's boundary.
 The horizontal flowpane arranges the nodes in a row
and wrap them according to the flowpane's width.
 The vertical flowpane arranges the nodes in a column
and wrap them according to the flowpane's height.
 FlowPane layout is represented by
javafx.scene.layout.FlowPane class.
We just need to instantiate this class to create the flowpa
ne layout.
JavaFX FlowPane
 There are various properties of the class which are
described in the table below.
Property Description Setter Methods
alignment The overall alignment of the setAlignment(Pos value)
flowpane's content.
columnHalignment The horizontal alignment of nodes setColumnHalignment(HPos
within the columns. Value)
hgap Horizontal gap between the columns. setHgap(Double value)

orientation Orientation of the flowpane setOrientation(Orientation


value)
prefWrapLength The preferred height or width where setPrefWrapLength(double
content should wrap in the horizontal value)
or vertical flowpane.
rowValignment The vertical alignment of the nodes setRowValignment(VPos
within the rows. value)
vgap The vertical gap among the rows setVgap(Double value)
JavaFX Layouts
Constructors
There are 8 constructors in the class that are given below.
 FlowPane()
 FlowPane(Double Hgap, Double Vgap)
 FlowPane(Double Hgap, Double Vgap, Node? children)
 FlowPane(Node... Children)
 FlowPane(Orientation orientation)
 FlowPane(Orientation orientation, double Hgap, Double
Vgap)
 FlowPane(Orientation orientation, double Hgap, Double
Vgap, Node? children )
 FlowPane(Orientation orientation, Node... Children)
JavaFX Layouts
import javafx.application.Application; for (int i=1; i<=20; i++) {
import javafx.geometry.Insets; root.getChildren().add(new Button
import javafx.geometry.Orientation; (String.valueOf(i)));
import javafx.scene.Scene; }
import javafx.scene.control.Button; Scene scene = new Scene(root, 300,
import javafx.scene.layout.FlowPane; 250);
import javafx.stage.Stage; stage.setTitle("FlowPane");
public class FlowPaneEx extends Application { stage.setScene(scene);
stage.show();
public void start(Stage stage) { }

initUI(stage); public static void main(String[] args) {


} launch(args);
private void initUI(Stage stage) { }
}
FlowPane root = new FlowPane(Orientation
.HORIZONTAL, 5, 5);
root.setPadding(new Insets(5));
JavaFX Layouts
JavaFX BorderPane
 BorderPane arranges the nodes at the left, right, centre, top and
bottom of the screen.
 It is represented by javafx.scene.layout.BorderPane class.
 This class provides various methods like setRight(), setLeft(),
setCenter(), setBottom() and setTop() which are used to set the
position for the specified nodes. We need to instantiate BorderPane
class to create the BorderPane layout.

Properties
Type Property Setter Methods Description
Node Bottom setBottom() Add the node to the bottom of the screen
Node Centre setCentre() Add the node to the centre of the screen
Node Left setLeft() Add the node to the left of the screen
Node Right setRight() Add the node to the right of the screen
Node Top setTop() Add the node to the top of the screen
JavaFX BorderPane

Constructors
 There are the following constructors in the class.
 BorderPane() : create the empty layout
 BorderPane(Node Center) : create the layout with the
center node
 BorderPane(Node Center, Node top, Node right, Node
bottom, Node left) : create the layout with all the nodes
JavaFX Layouts
import javafx.application.Application;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
public class Layout1 extends Application{
public static void main(String[] s) {
launch(s);
}
public void start(Stage ps) throws Exception{
ps.setTitle("Border Pane");
BorderPane bp=new BorderPane();
Button b1=new Button("First"); bp.setTop(b1);
Button b2=new Button("Second"); bp.setBottom(b2);
Button b3=new Button("Third"); bp.setRight(b3);
Button b4=new Button("Four"); bp.setLeft(b4);
Button b5=new Button("Five"); bp.setCenter(b5);
Scene s1=new Scene(bp,500,500);
ps.setScene(s1);
ps.show(); } }
JavaFX Layouts
JavaFX HBox
 HBox layout pane arranges the nodes in a single row.
 It is represented by javafx.scene.layout.HBox class.
Properties
Property Description Setter Methods

alignment This represents the alignment of the nodes. setAlignment(Double)

fillHeight This is a boolean property. If you set this pro setFillHeight(Double)


perty to true the height of the nodes will bec
ome equal to the height of the HBox.

spacing This represents the space between the node setSpacing(Double)


s in the HBox. It is of double type.

Constructors
 The HBox class contains two constructors that are given below.
 new HBox() : create HBox layout with 0 spacing
 new Hbox(Double spacing) : create HBox layout with a spacing
value
JavaFX Layouts
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Label_Test extends Application {

public void start(Stage primaryStage) throws Exception {


Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
HBox root = new HBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
root.setSpacing(40);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
} }
JavaFX Layouts
JavaFX VBox
 Instead of arranging the nodes in horizontal row, Vbox Layout
Pane arranges the nodes in a single vertical column.
 It is represented by javafx.scene.layout.VBox class which provides
all the methods to deal with the styling and the distance among the
nodes.
Properties

Property Description Setter Methods

Alignment This property is for the alignment of the nodes. setAlignement(Double)

FillWidth This property is of the boolean type. The Widtht of setFillWidth(boolean)


resizeable nodes can be made equal to the Width
of the VBox by setting this property to true.

Spacing This property is to set some spacing among the n setSpacing(Double)


odes of VBox.
JavaFX VBox
Constructors

 VBox() : creates layout with 0 spacing


 Vbox(Double spacing) : creates layout with a spacing value of
double type
 Vbox(Double spacing, Node? children) : creates a layout with
the specified spacing among the specified child nodes
 Vbox(Node? children) : creates a layout with the specified
nodes having 0 spacing among them
JavaFX VBox
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Label_Test extends Application {

public void start(Stage primaryStage) throws Exception {


Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
VBox root = new VBox();
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);
}
}
JavaFX VBox
JavaFX GridPane
 GridPane Layout pane allows us to add the multiple nodes in
multiple rows and columns. It is seen as a flexible grid of rows and
columns where nodes can be placed in any cell of the grid.
 It is represented by javafx.scence.layout.GridPane class.
Properties
Property Description Setter Methods
alignment Represents the alignment of the grid within the setAlignment(Pos value)
GridPane.
gridLinesVisible This property is intended for debugging. Lines can setGridLinesVisible(Boolean
be displayed to show the gidpane's rows and value)
columns by setting this property to true.

hgap Horizontal gaps among the columns setHgap(Double value)


vgap Vertical gaps among the rows setVgap(Double value)

Constructors
 The class contains only one constructor that is given below.
 Public GridPane(): creates a gridpane with 0 hgap/vgap.
JavaFX GridPane
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 Label_Test extends Application {
public void start(Stage primaryStage) throws Exception {
Label first_name=new Label("First Name");
Label last_name=new Label("Last Name");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button Submit=new Button ("Submit");
GridPane root=new GridPane();
Scene scene = new Scene(root,400,200);
root.addRow(0, first_name,tf1); root.addRow(1, last_name,tf2);
root.addRow(2, Submit); primaryStage.setTitle("Grid Pane Example");
primaryStage.setScene(scene); primaryStage.show();
}
public static void main(String[] args) {
launch(args);
} }
JavaFX GridPane
JavaFX 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.
Properties
 The class contains only one property that is given below along with
its setter method.
Constructors
 The class contains two constructors that are given below.
 StackPane()
 StackPane(Node? Children)

Property Description Setter Method

alignment It represents the default align setAlignment(Node child


ment of children within the Sta , Pos value)
ckPane's width and height setAlignment(Pos value)
Absolute layout
 To create a more complex layout, it is possible to nest different
containers within a JavaFX application.
 Except for the GridPane, built-in layout managers are very basic and
are not suited for more complex applications.
 More complicated layouts should use either the GridPane or the third-
party MigPane.
 The Pane node can be used to position nodes in absolute
coordinates. Complex layouts should be always created using layout
managers;
 absolute layout is used in specific situations (for instance, positioning
charts or images).
 MigPane is a very powerful third-party layout manager. It uses
the MigLayout manager, which is available for Swing, SWT, and
JavaFX. It is highly recommended to consider this manager.
Absolute layout
 To use the MigPane, it is necessary to include the JARs to the project
libraries. The JARs for sources and javadoc are optional.
 MigPane uses string constraints to do the layout. There are four kinds
of constraints: general constraints, column constraints, row
constraints, and control constrains.
 There are several layout modes in MigPane. The grid mode is the
default one and is the most flexible of the available modes.
Absolute layout
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class AbsoluteLayoutEx extends Application {
public void start(Stage stage) {
initUI(stage);
}
private void initUI(Stage stage) {
Pane root = new Pane();
Rectangle rect = new Rectangle(25, 25, 50, 50);
rect.setFill(Color.CADETBLUE);
Line line = new Line(90, 40, 230, 40);
line.setStroke(Color.BLACK);
Circle circle = new Circle(130, 130, 30);
circle.setFill(Color.CHOCOLATE);
root.getChildren().addAll(rect, line, circle);
Scene scene = new Scene(root, 250, 220, Color.WHITESMOKE);
stage.setTitle("Absolute layout");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Absolute layout
JavaFX – Event Handling
 In event-driven programming, code is executed upon activation of
events.
 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
 The Operating Systems (OS) constantly monitor events (e.g.,
keystrokes, mouse clicks), the OS sorts out these events by the
program on which the event was detected, and reports them to that
program
 The program (the JVM in our case) will run the event handler for
the GUI component that was interacted with OS
 we define an event handler class (a.k.a. an event listener) with a
method with the code to respond to the event, we construct an
instance of the event handler and we tell the control who its event
handler is.
 The event handler implements the appropriate interface
JavaFX – Event Handling
 The GUI component/control is called the event source
 JavaFX: Button, ChoiceBox, ListView, etc.

 When the user interacts with a control:


 an event object is constructed
 the event object is sent to all registered event handler objects
for that control and the handler object will respond as you
defined it
JavaFX – Event Handling
 Source object: button
 An event is generated by external user actions such as mouse
clicks, mouse movements, or keystrokes.
 An event can be defined as a type of signal to the program that
something has happened.
 Listener object contains a method for processing the event.
JavaFX – Event Handling
All Events are subclasses of Event.
Event
EventHandler properties along with their setter methods
ActionEvent
InputEvent
KeyEvent
MouseEvent
WebEvent

WindowEvent
JavaFX – Event Handling
 Source object: button

 For Example,
Button bt = new Button(“Click the button");

bt.setOnAction(new EventHandler<ActionEvent>()
{
public void handle (ActionEvent ae)
{

}
}
….

 Separate classes also create for event handlers and that class object
assigned to source object.
JavaFX – Event Handling
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.scene.control.Alert;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
public class HandleEvent extends Application {
public void start(Stage primaryStage) {
HBox pane = new HBox(10);
Button btOK = new Button("OK");
Button btCancel = new Button("Cancel");
OKHandlerClass handler1 = new OKHandlerClass();
btOK.setOnAction(handler1);
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);
pane.getChildren().addAll(btOK, btCancel);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} }
JavaFX – Event Handling
class OKHandlerClass implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
Alert a = new Alert(Alert.AlertType.INFORMATION);
a.setContentText("OK button clicked");
System.out.println("OK button clicked");
a.show();
}
}
class CancelHandlerClass implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
Alert a = new Alert(Alert.AlertType.CONFIRMATION);
a.setContentText("CANCEL button clicked");
System.out.println("Cancel button clicked. ");
a.show();
}}
JavaFX – Event Handling
JavaFX – Event Handling
 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.
 The Node class has a wide range of event listeners for the different
types of events.
 Handily they are prefixed by what event they listen for, so all mouse
event listeners begin with .onMouse, all key event listeners begin
with .onKey.
 The mouseEvent object that got passed in contains information
about the event such as the x & y position.
 The events you get are:
1. Mouse Pressed
2. Mouse Dragged
3. Mouse Released
4. Mouse Clicked
JavaFX – Event Handling
setOnMousePressed(new EventHandler() {
public void handle(MouseEvent e) {
pageClickEvent = true; }
});

setOnMouseDragged(new EventHandler() {
public void handle(MouseEvent e) {
pageClickEvent = false; }
});

setOnMouseReleased(new EventHandler() {
public void handle(MouseEvent e) {
if (pageClickEvent) {
goTo(page);
pageClickEvent = false;
} }
});
JavaFX – Event Handling
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
public class MouseEv extends Application {
Path path;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
path = new Path();
path.setStrokeWidth(1);
path.setStroke(Color.BLACK);
JavaFX – Event Handling
scene.setOnMouseClicked(mouseHandler);
scene.setOnMouseDragged(mouseHandler);
scene.setOnMouseEntered(mouseHandler);
scene.setOnMouseExited(mouseHandler);
scene.setOnMouseMoved(mouseHandler);
scene.setOnMousePressed(mouseHandler);
scene.setOnMouseReleased(mouseHandler);
root.getChildren().add(path);
primaryStage.setScene(scene);
primaryStage.show();
}
JavaFX – Event Handling
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>()
{
public void handle(MouseEvent mouseEvent)
{
System.out.println(mouseEvent.getEventType() + “\n"
+ "X : Y - " + mouseEvent.getX() + " : " + mouseEvent.getY() +" \n"
+ "SceneX : SceneY - " + mouseEvent.getSceneX() + " : " +
mouseEvent.getSceneY() + " \n” + "ScreenX : ScreenY - " +
mouseEvent.getScreenX() + " : " + mouseEvent.getScreenY());
}};
}
JavaFX – Event Handling
JavaFX – Event Handling
 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 is generated when a key is pressed, released, or typed.
Depending on the type of the event it is passed
to onKeyPressed, onKeyTyped or onKeyReleased function.
 "Key typed" events are higher-level and generally do not depend on
the platform or keyboard layout.
 In the simplest case, a key typed event is produced by a single key
press (e.g., 'a').
 No key typed events are generated for keys that don't generate
Unicode characters (e.g., action keys, modifier keys, etc.).
 "Key pressed" and "key released" events are lower-level and
depend on the platform and keyboard layout.
JavaFX – Event Handling
textField.setOnKeyPressed(new EventHandler<KeyEvent>()
{
public void handle(KeyEvent ke)
{
if (ke.getCode().equals(KeyCode.ENTER))
{
…..
} } });

Example: import javafx.application.Application;


import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.*;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
JavaFX – Event Handling
public class KeyEv extends Application{
public void start(Stage primaryStage) throws Exception
{
Text t1 = new Text(20,20,"Press any key from Keyboard...");
Text t2 = new Text(50,50," ");
t2.setFont(Font.font("Arial",FontWeight.BOLD,30));
t2.setOnKeyPressed(e->{t2.setText(e.getText()); });
Group root = new Group(t1,t2);
Scene scene = new Scene(root,500,200,Color.WHEAT);
primaryStage.setScene(scene);
primaryStage.setTitle("Handling KeyEvent");
primaryStage.show();
t2.requestFocus();
}
public static void main(String[] args) {
launch(args);
}
}
JavaFX – Event Handling
JavaFX – Event Handling
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class KeyEvent extends Application{
public void start(Stage primaryStage) throws Exception {

TextField tf1 = new TextField();


TextField tf2 = new TextField();
tf1.setTranslateX(50);
tf1.setTranslateY(50);
tf2.setTranslateX(50);
tf2.setTranslateY(100);
JavaFX – Event Handling

//Handling KeyEvent for textfield 1


tf1.setOnKeyPressed(e->{tf2.setText("Key Pressed :"+" "+e.getText());});

Group root = new Group();


root.getChildren().addAll(tf2,tf1);
Scene scene = new Scene(root,500,200,Color.WHEAT);
primaryStage.setScene(scene);
primaryStage.setTitle("Handling KeyEvent");
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}
JavaFX – Event Handling
JavaFX – Event Handling
JavaFX – Menu
 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. A menu bar is a user interface element that holds all
the menus, it is usually placed on the top.
 In JavaFX the javafx.scene.control.MenuBar class represents a
menu bar. You can create a menu bar by instantiating this class.
 A Menu is a list of options or commands presented to the user.
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.
JavaFX – Menu
Constructor of the MenuBar class are:
 MenuBar(): creates a new empty menubar.
 MenuBar(Menu… m): creates a new menubar with the given set of
menu.
Constructor of the Menu class are:
 Menu(): creates an empty menu
 Menu(String s): creates a menu with a string as its label
 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.
 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.
JavaFX – Menu
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 v) Sets the value of the property useSystemMenuBar.

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
Steps to implementation of JavaFX menu

//creating MenuBar
ManuBar menubar = new MenuBar();
//creating Menu
Menu MenuName = new Menu("Menu Name");
//creating Menu Item
MenuItem MenuItem1 = new MenuItem("Menu Item 1 Name");
//adding Menu Item to the Menu
MenuName.getItems().add(MenuItem1);
//adding Menu to the MenuBar
menubar.getMenus().add(MenuName);
JavaFX – Menu
import javafx.application.Application;
import javafx.scene.Scene; import javafx.scene.control.*;
import javafx.scene.layout.BorderPane; import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene); primaryStage.show(); } }
JavaFX – Menu
JavaFX – Menu
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AddingSubMenu extends Application {
public void start(Stage primaryStage) {
primaryStage.setTitle("Adding Items to Menu Bar");
MenuBar menuBar=new MenuBar(); //creating menu bar
//creating menu for adding menu items
Menu menu=new Menu("Show");
MenuItem companyName=new MenuItem("PSNACET"); //creating menu items
MenuItem aboutPSNA=new MenuItem("About PSNACET");
MenuItem feeStructure=new MenuItem("Fee Structure");
//sub menu items for the courses
MenuItem javCourse=new MenuItem("Java");
MenuItem pythonCourse=new MenuItem("Python");
MenuItem cCourse=new MenuItem("C");
MenuItem angularCourse=new MenuItem("Angular JS");
//adding menu items to the menu
menu.getItems().add(companyName);
menu.getItems().add(aboutPSNA);
menu.getItems().add(feeStructure);
JavaFX – Menu
//adding sub menu items to the course menu
Menu subMenuCourse=new Menu("All Courses");
subMenuCourse.getItems().add( javCourse);
subMenuCourse.getItems().add(pythonCourse);
subMenuCourse.getItems().add(cCourse);
subMenuCourse.getItems().add(angularCourse);
menu.getItems().add(subMenuCourse);
//adding menu to the menu bar
menuBar.getMenus().add(menu);
//creating VBox for adding all menu bar
VBox vBox=new VBox(menuBar);
//adding scroll pane to the scene
Scene scene = new Scene(vBox, 401, 201);
primaryStage.setScene(scene);
//showing the output
primaryStage.show();
}
public static void main(String[] args) {
//invoking main method from JVM
launch(args);
} }
JavaFX – Menu
JavaFX – Menu
import javafx.application.Application; import javafx.event.ActionEvent;
import javafx.event.EventHandler; import javafx.scene.Scene;
import javafx.scene.control.Label; import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem;
import javafx.scene.layout.Vbox; import javafx.stage.Stage;
public class AddingMenuEvent extends Application {
public void start(Stage primaryStage) {
primaryStage.setTitle("Adding Events to Menu items");
MenuBar menuBar=new MenuBar(); //creating menu bar
Menu menu=new Menu("Show"); //creating menu for adding menu items
MenuItem companyName=new MenuItem("PSNACET"); //creating menu items
MenuItem courses=new MenuItem("Courses");
MenuItem aboutPSNACET=new MenuItem("About PSNACET");
MenuItem feeStructure=new MenuItem("Fee Structure");
//adding menu items to the menu
menu.getItems().add(companyName);
menu.getItems().add(courses);
menu.getItems().add(aboutPSNACET);
menu.getItems().add(feeStructure);
menuBar.getMenus().add(menu); //adding menu to the menu bar
Label selectionLabel=new Label(); //creating label for adding menu item selection
JavaFX – Menu
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
selectionLabel.setText(“ You have " +((MenuItem)e.getSource()).getText() +" item
selected");
} };
companyName.setOnAction(event); //adding event to the menu items
courses.setOnAction(event);
aboutPSNACET.setOnAction(event);
feeStructure.setOnAction(event);
//creating VBox for adding all menu bar
VBox vBox=new VBox(menuBar, selectionLabel);
//adding scroll pane to the scene
Scene scene = new Scene(vBox, 401, 201);
primaryStage.setScene(scene);
//showing the output
primaryStage.show();
}
public static void main(String[] args) {
//invoking main method from JVM
launch(args); }}
JavaFX – Menu
JavaFX – Menu

You might also like