[Go to site: main page, start]

0% found this document useful (0 votes)
5 views84 pages

Introduction to JavaFX GUI Programming

Uploaded by

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

Introduction to JavaFX GUI Programming

Uploaded by

birukgetu800
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

GUI

By Muluken W.
GUI Applications
 So far, you’ve probably only worked on
console applications
 Provide input from keyboard

 Read input using [Link]

 Do something

 Print result to [Link]

 It’ll be nice to have a GUI application


 Examples: Microsoft Word, Apps on your

phone, Your browser


 We cover the basic material before covering
GUI programming because it requires use of
all the basic knowledge you’ve learned so far
GUI Applications

 You’ve learned most of the basic concepts


of Java
 You should be able to pick up any library,
do some research, and use it in your project
 From now and on, there are too many
methods available in the libraries that
we’re covering, we will not go over all of
them in class
 It’s up to you to figure it out
 We will cover JavaFX in this class
Motivations
 A graphical user interface (GUI) makes a
system user-friendly and easy to use.
 Creating a GUI requires creativity and

knowledge of how GUI components work.


 Since the GUI components in Java are very

flexible and versatile, you can create a wide


variety of useful user interfaces.
 This chapter introduces the frequently used GUI

 components
JavaFX is thein Evolution
detail. of Java as a Rich
Client Platform.
 It is designed to provide a modern Java
environment featuring a lightweight,
hardware accelerated UI platform that
JavaFX vs Swing vs AWT
 Java was first released with GUI support in
something called the Abstract Windows
Toolkit (AWT)
 AWT wasn’t bad, but it had some
limitations, and some particular problems
with how it was implemented on some
platforms.
 Ultimately, AWT (which still exists, but isn’t
used much anymore) was replaced by a
new library called Swing, which was more
versatile, more robust, and more flexible.
JavaFX vs Swing vs AWT…
 Swing was designed primarily for use in
desktop applications (although you could
do some web-based things with it, too).
 Swing has now been replaced by a
completely new GUI library called JavaFX
 You can still use Swing (for the foreseeable
future), but Oracle isn’t going to develop it
any further – it’s essentially a dead-end
technology
 Java has replaced Swing with JavaFX
 How long until JavaFX is replaced by
something else?
JavaFX vs Swing vs AWT…
 JavaFX lets us write RIAs (Rich Internet
Applications), which essentially run under
a browser (IE / FireFox / Chrome / Safari)
just like they run on a desktop
 Previously, the cross-platform (desktop vs
browser) experience was delivered by Java
Applets, but applets are pretty much dead,
too.
 If you need to learn Swing, I will provide
lecture slides or lecture note; otherwise,
just learn JavaFX, and don’t look back.
What Can I Build with JavaFX?
 With JavaFX, you can build many types of
applications.
 Typically, they are network-aware applications

that are deployed across multiple platforms and


display information in a high-performance
modern user interface that features audio,
video, graphics, and animation.
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..
 Need for JavaFX
 To develop Client Side Applications with rich

features, the programmers used to depend on


various libraries to add features such as Media,
UI controls, Web, 2D and 3D, etc.
 JavaFX includes all these features in a single

library.
Features of JavaFX
 Let see 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, which include − Java, Groovy
and JRuby. These JavaFX applications are also
platform independent.
 FXML − JavaFX features a language known as
FXML, which is a HTML like declarative markup
language. The sole purpose of this language is to
define a user Interface.
 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


… Features of JavaFX
 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 [Link] it
… Features of JavaFX
 Rich set of API’s − JavaFX library provides a rich
set of API’s to develop GUI applications, 2D and 3D
graphics, etc.
 Using this API, you can access the features of Java

languages such as Generics, Annotations,


Multithreading, and Lambda Expressions.
 The traditional Java Collections library was

enhanced and concepts like observable lists and


maps were included in it.
 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.
… Features of JavaFX
 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.
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 −
1. [Link] − Contains classes to add transition
based animations such as fill, fade, rotate, scale and
translation, to the JavaFX nodes.
2. [Link] − Contains a set of classes
responsible for the JavaFX application life cycle such as:
Init(), start(), stop() method.
3. [Link] − Contains classes to add CSS–like styling to
JavaFX GUI applications.
4. [Link] − Contains classes and interfaces to
deliver and handle JavaFX events.
5. [Link] − Contains classes to define 2D and
3D such as circle, rectangle, polygon, etc. and perform
operations on them.
6. [Link] − This package holds the top level
container classes for JavaFX application.
Scene Graph
 It provides sub-packages such as canvas, chart,
control, effect, image, input, layout, media, paint,
shape, text, transform, web, etc.
 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,
… Scene Graph
 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.
 A Group class is the subclass of Node, whose
purpose is to group several node objects in to a
single act.

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. This
component supports different web technologies like
HTML5, CSS, JavaScript, DOM and SVG.
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 [Link] contains the
classes and interfaces to provide media
in the •MP3
functionality in JavaFX. It is providedAudio form of
•WAV
three components, which are − •AIFF

Video •FLV

 Media Object − This represents a media file


 Media Player − To play media content.
Basic Structure of JavaFX
 Application
 Override the start(Stage) method
 Stage
 Represents windows, top level container

 Many setter methods: setTitle(), setWidth()

 You can create multiple stages and use one or another

 Scene
 Each stage has a scene

 Scene holds controls (buttons, labels, etc)

 Pane
 You can put controls in Scenes directly, but we usually

Panes for better layout


 Examples: StackPane, BorderPane, HBox, VBox
JavaFX Programs: Basic Structure

public class MyProgram


{
// Body of class
}

Becomes:

import [Link];

public class MyProgram extends Application
{
// Body of class
}
JavaFX HelloWorld Example: Start
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}

• Starting Point of a
// Override the start method in the Application class
@Override
JavaFX application
public void start(Stage primaryStage) {
• Main Method can be
// Create a scene and place a button in the scene omitted when
Button btOK = new Button("OK"); running from
Scene scene = new Scene(btOK, 200, 250); console/with
[Link]("MyJavaFX");//Set the stage title e(fx)clispe installed
[Link](scene); // Place the scene • A primary stage is
[Link](); created
} automatically
• Place the scene in the • Individual UI
}
Stage components are
• [Link]() makes called controls
window appear • Example: Labels,
Multiple Stages

 In JavaFX, the stage is the window our code runs in


 Since every GUI application, by definition, involves
a window with the UI, we get the primaryStage by
default when the application launches.
 Our applications are not limited to a single stage
 Just as a music festival may have simultaneous
performances on multiple stages, we can have
more than one stage (window) in our programs.
 The code to set
up this two-
stage UI is on
the next slide
import [Link];
import [Link];
import [Link];
import [Link];
public class MultipleStageDemo extends Application
{
@Override // 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);
[Link]("MyJavaFX"); // Set the stage
title
[Link](scene); // Put the scene
in the stage
[Link](); // Display the stage
Stage stage = new Stage(); // Create a new
Default stages
 By default, stages (windows) are resizeable.
 Note that we have minimize and maximize
buttons
 If we want our stage to be of fixed size (i.e.,
not resizeable),
we can set that property with
[Link](false)
Panes
 We can put the button directly on the scene,
which centered the button and made it occupy
the entire window.
 Rarely is this what we really want to do
 One approach is to specify the size and
location of each UI element (like the buttons)
 A better solution is to
put the UI elements
(known as nodes)
into containers called
panes, and then add
the panes to the scene.
Panes…
Panes can even contain other panes:
Layout Panes
 JavaFX provides many types of panes for organizing
nodes in a container.
 As we’ve said (and have been doing), we add our
Nodes to a Pane, and then add the Pane to a Scene,
and then the Scene to a Stage (probably the
primary stage).
 How do we arrange (i.e., lay out) the Nodes on the
pane?
 Java has several different kinds of Panes that do a
lot of the layout work for us.
 This section examines these layout panes in more
detail
 We’ve already used the Pane , HBox, and
StackPane; we’ll start with the FlowPane…
Layout Panes…
Name Description
Pane Base class for layout panes. Use its getChildren()
method to return the list of nodes on the pane (or
add to that list)
Provides no particular layout capabilities – it’s a
“blank canvas” typically used to draw shapes on
StackPane Places nodes on top of each other in the center of the
pane
FlowPane Places the notes row-by-row horizontally or column-
by-column vertically (reading order)

GridPane Provide a 2-D grid of cells, into which we can place


nodes
BorderPan Divides pane into top, bottom, left, right, and center
e regions
HBox Places nodes in a single (horizontal) row
FlowPane
 The FlowPane can be set up to work in
“reading order” (sequential rows left-to-right),
by using [Link] or in
sequential top-to-bottom columns
([Link])
 You can also specify the gap between nodes
(in pixels)
 So far, we have seen putting Button nodes on
a pane.
 uses the FlowPane and Label & TextField
nodes.
 Let’s take a closer look…
FlowPane …
public void start(Stage primaryStage) // From Listing 14.10 (p.
553)
{
// Create a pane and set its properties
FlowPane pane = new FlowPane();
[Link](new Insets(11, 12, 13, 14));
[Link](5);
[Link](5);

// Place nodes in the pane


[Link]().addAll(new Label("First Name:"),
new TextField(), new Label("MI:"));
TextField tfMi = new TextField();
[Link](1);
[Link]().addAll(tfMi, new Label("Last Name:"),
new TextField());

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 200, 250);
[Link]("ShowFlowPane"); // Set the stage title
[Link](scene); // Put scene in stage
[Link](); // Display the stage
FlowPane …
public void start(Stage primaryStage) Setting the padding
{ with an Insets object
// Create a pane and set its properties gives us a margin
FlowPane pane = new FlowPane(); inside the pane. Just
[Link](new Insets(11, 12, 13, as14));
angles are always
[Link](5); clockwise, the Insets
[Link](5); are specified in
clockwise order from
// Place nodes in the pane the top, so this pane
[Link]().addAll(new Label("Firstwill
Name:"),
have an 11-pixel
new TextField(), new Label("MI:")); gap between the top
TextField tfMi = new TextField(); of the pane and the
[Link](1); first row, a 12-pixel
[Link]().addAll(tfMi, new Label("Last Name:"),
gap between the right-
new TextField()); most node and the
right side of the pane,
// Create a scene and place it in the stage 13 pixels at the
Scene scene = new Scene(pane, 200, 250); bottom, and 14 pixels
[Link]("ShowFlowPane"); //on Set
thethe stage
left [Link]
[Link](scene); // Put scene
The Hgapin stage
and Vgap
[Link](); // Display the stage specify the
properties
} gap between elements
FlowPane …
This example introduces two
public void start(Stage primaryStage) new nodes: Label (which just
{ // Create a pane and set its properties
lets us display text on a
FlowPane pane = new FlowPane();
[Link](new Insets(11, 12, 13,pane),
14)); and TextField (which
[Link](5); provides a box into which the
[Link](5); user can type text).

// Place nodes in the pane TextField nodes typically have


a corresponding
[Link]().addAll(new Label("First Label, so the
Name:"),
new TextField(), new userLabel("MI:"));
can tell what’s supposed
TextField tfMi = new TextField(); to go IN the TextField
[Link](1);
[Link]().addAll(tfMi, new Label("Last Name:"),
new TextField());
We can .add() individual nodes
to a pane, or we can .addAll()
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 200,to250); add a list of nodes, as is
[Link]("ShowFlowPane"); done here.
[Link](scene); We add a Label of “First
[Link]();} Name:”, and then a TextField
into which the user can type
FlowPane …
public void start(Stage primaryStage)
Finally, we go back to the task
{ of adding the (narrow) Middle
// Create a pane and set its properties
FlowPane pane = new FlowPane();Initial TextField, plus a Label
[Link](new Insets(11, 12,and13,a TextField
14)); for the last
[Link](5); name to the pane.
[Link](5); Now we have Label / TextField
// Place nodes in the pane pairs for First Name, Middle
[Link]().addAll(new Initial (a one-character-wide
Label("First Name:"),
TextField),
new TextField(), and Last Name
new Label("MI:"));
TextField tfMi = new TextField();
[Link](1);
[Link]().addAll(tfMi, new Label("Last Name:"),
new TextField());

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 200, 250);
[Link]("ShowFlowPane"); // Set the stage title
[Link](scene); // Put scene in stage
[Link](); // Display the stage
FlowPane …
 This is the stage we have built:

 Because we went in “reading order”, and


added the nodes in the order we did, we got
this – the “MI:” label is next to the tfMi
TextField in reading order, but this isn’t
visually appealing.
FlowPane …

 If we make the scene wider (enlarge the


window)

 The elements “re-flow”, and now the MI


TextField fits on the same row as its Label
GridPane
 The GridPane divides the pane’s area into a 2-
D grid of rows and columns.
 The previous example redone, with the three
Labels in the left column, and the three
TextFields (note that the author did not bother
to make the MI TextField narrow in this
example)
The BorderPane

 The BorderPane divides the


pane into five “regions”
 The program places a CustomPane
in each region.
 The CustomPane is an extension of StackPane,
which is used to display the labels
 Note that a Pane is also a Node, so a Pane can
contain another Pane
 If a region is empty, it’s simply not shown
 We can clear a region with set<region>(null)
HBox and VBox
 HBoxThe HBox layout arranges all the nodes in our
application in a single horizontal row.
 The class named HBox of the
package [Link] represents the text
horizontal box layout.
 VBoxThe VBox layout arranges all the nodes in our
application in a single vertical column.
 The class named VBox of the
package [Link] represents the text
Vertical box layout.
Frequently Used UI Controls

• A label is a display area for a short text, a node, or


both.
• It is often used to label other controls (usually text
fields).
• See ‘Enter a new message’ is from the next slide
A text field can be used to
enter or display a string.
Radio buttons, also
known as option buttons,
enable you to choose a
single item from a group of
choices. In appearance
radio buttons resemble
check boxes, but check
boxes display a square that
is either checked or blank,
whereas
A buttonradio buttonsthat
is a control
display
triggersaan circle that
action is
event A CheckBox is used for the
either filled (if JavaFX
when clicked. selected) or user to make a selection. Like
blank (if not selected). Button, CheckBox inherits all
provides regular buttons, the properties such as
toggle buttons, check box onAction, text, graphic,
buttons, and radio buttons. alignment, graphicTextGap,
The common features of textFill, contentDisplay from
UI Controls … ScrollBar
A scroll bar is a control that enables the user to
select from a range of values. The scrollbar
appears in two styles: horizontal and vertical.
Scroll Bar
Properties

See the next example which uses horizontal


and vertical scrollbars to control a message
displayed on a panel. The horizontal scrollbar
is used to move the message to the left or
the right, and the vertical scrollbar to move it
UI Controls … combo box & TextArea

A combo box, also known as a choice list or


drop-down list, contains a list of items from
which the user can choose.

A TextArea enables the user to enter


multiple lines of text.
UI Controls … ListView

A listview is a component that performs


basically the same function as a combo box,
but it enables the user to choose a single
value or multiple values.
UI Controls … Sliders
Slider is similar to ScrollBar, but Slider has more
properties and can appear in many forms.
Rewrite the
preceding program
using the sliders to
control a message
displayed on a panel
instead of using
scroll bars.
Datepicker
The Image & ImageView Classes

 We used the File class to hold information


about a file, but not to actually read / write to
it
 For that we used a Scanner / PrintWriter,
connected to the File object
 Similarly, the Image class is a container for an

image, but can’t be used to actually display an


image
We
 construct
For that, we anuse
Image from a filename
the ImageView node (or a
(and
URL),
attachand
it tothen we can give the Image to an
a scene)
ImageView object to actually display it
The Image & ImageView Classes
public class image extends Application {
@Override
public void start(Stage stage) throws FileNotFoundException {
//Creating an image
Image image = new Image(new FileInputStream("C:\\Users\\
Abuyasmin\\Desktop\\save_spend\\[Link]"));
ImageView imageView = new ImageView(image);
[Link](200); // fit into 200-x-200
[Link](200);
//Creating a Group object
Group root = new Group(imageView);
//Creating a scene object
Scene scene = new Scene(root, 600, 500);
//Setting title to the Stage
[Link]("image ");
//Adding scene to the stage
[Link](scene);
//Displaying the contents of the stage
[Link]();
}
JavaFX | MenuBar and Menu
 MenuBar is usually placed at the top of the
screen which contains several menus.
 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.
Example of MenuBar and
Menu
public void start(Stage s)
{
[Link]("creating MenuBar"); // set title for the stage
MenuItem m1 = new MenuItem("menu item 1"); // create
menuitems
MenuItem m2 = new MenuItem("menu item 2");
MenuItem m3 = new MenuItem("menu item 3");
Menu m = new Menu("Menu"); // create a menu
[Link]().add(m1); // add menu items to menu
[Link]().add(m2);
[Link]().add(m3);
MenuBar mb = new MenuBar(); // create a menubar
[Link]().add(m); // add menu to menubar
VBox vb = new VBox(mb); // create a VBox
Scene sc = new Scene(vb, 500, 300); // create a scene
[Link](sc); // set the scene
Shapes

JavaFX provides many shape classes for


drawing texts, lines, circles, rectangles,
ellipses, arcs, polygons, and polylines.

All of the shapes have some


common properties:
fill (color)
stroke (line color)
strokeWidth (how heavy the
stroke line is)
Shapes…
 Beyond the obvious, typical “active” UI
elements (things we can interact with, like
buttons, etc.), are static shapes – lines, circles,
etc.
 Before we can do much with shapes, we have
to talk about coordinates within a pane.
 The top-left corner of a scene is always (0, 0), and the
(positive) X-axis goes
to the right, and the (positive) Y-axis goes
down. Visually, we’re in
Cartesian quadrant IV,
but Y stays positive.
 All coordinates are in pixels
Shapes…

 Text - the text we place as a Shape can


have its color, font (typeface, weight, size,
and posture), underline, and strikethrough
properties set.
 This is different from a Label’s JavaFX

CSS properties
 Once placed, we can move text by using
setX() and setY() to give it a new location
 Line - Each line is specified by its two
endpoints: startX, startY and endX, endY
(all doubles, in pixels)
Shapes… Rectangle
 The Rectangle shape is specified by its top-left
corner (x, y) and its width and height.
 Optionally, we can specify the arcWidth and
arcHeight (in pixels) of the corners, to create
rounded corners (arc measurements of 0 make
squared-off corners)
Shapes… Circle and Ellipse

 The Circle and Ellipse shapes are very similar,


as you might expect
 Both are specified by their center point
(centerX, centerY)
 The Circle has a single radius
 The Ellipse has two radii (radiusX & radiusY)
Shapes… Arc
 An Arc is just part of an Ellipse
 An Arc is specified by its center point, radii,
start angle (in degrees), and length (in
degrees)
 If the two radii are equal, then it’s a circular

arc
 Angles may be negative (clockwise sweep)
Shapes… Polygon and Polyline

 The Polygon and Polyline shapes are identical,


except that the Polyline isn’t closed
 Both are specified by a list of (x, y) pairs
Shapes… Polygon and Polyline

 If we know all of the points up-front, we can


specify them as a variable-length parameter
list:
Polygon p = new Polygon(x1, y1, x2, y2, …);
 If we don’t know all of the points a priori, the
Polygon exposes an ObservableList to which
we can add points (i.e., generate the points
on-the-fly and add them to the list as we go)
Shapes… Polygon and Polyline
Pane pane = new Pane(); // create a pane
Polygon polygon = new Polygon(); // create a polygon
[Link]().add(polygon); // add the polygon to the pane
[Link]([Link]); // polygon will be filled in white
[Link]([Link]); // with a black border
ObservableList<Double> list = [Link](); // get its vertex
list

final double WIDTH = 200, HEIGHT = 200; //


double centerX = WIDTH / 2, centerY = HEIGHT / 2; //
double radius = [Link](WIDTH, HEIGHT) * 0.4; //

// Generated and add (x, y) points to the polygon’s vertex list


for (int i = 0; i < 6; i++)
{ [Link](centerX + radius * [Link](2 * i * [Link] / 6));
[Link](centerY - radius * [Link](2 * i * [Link] / 6));
}
// Create a scene and place it in the stage
Scene scene = new Scene(pane, WIDTH, HEIGHT);
[Link]("ShowPolygon"); // Set the stage title
[Link](scene); // Put scene in stage
[Link](); // Display the stage
Media

You can use the Media class to obtain the source of


the media, the MediaPlayer class to play and control
the media, and the MediaView class to display the
video. MediaPlayer
The MediaPlayer class playes and controls the media
with properties such as autoPlay, currentCount,
cycleCount, mute, volume, and totalDuration.
MediaView
The MediaView class is a subclass of Node that
provides a view of the Media being played by a
MediaPlayer. The MediaView class provides the
Example: Using Media
This example displays a
video in a view. You can
use the play/pause
button to play or pause
the video and use the
rewind button to restart
the video, and use the
slider to control the
volume of the audio.
JavaFX Events
 Clicking on a button usually triggers an event. For
example, clicking the print button on the print
dialog we meant to print a document to printer. UI
library uses the events to notify something
happened.
 JavaFX event is an instance of the [Link] class or
its subclass.
 JavaFX provides several events, including

ActionEvent

InputEvent

ScrollToEvent

SortEvent

MediaErrorEvent

[Link]

TransformChangedEvent

Events…
 You can define your own event by extending
the Event class.
The following
Property table lists properties from Event
Description
type Type of event that occurred. For example, mouse event.
Source Origin of the event.
Target Last Node in the event dispatch chain.

 An event type is an instance of the EventType


class. For example, the KeyEvent class
contains the following event types:
 KEY_PRESSED
 KEY_RELEASED

Event-type vs Event-Class
 Event-type is the type of event that the handler
processes, for example, setOnKeyTyped for Key
Typed events or setOnMouseClicked for Mouse
Clicked events.
 event-class is the class that defines the event

type, for example, KeyEvent for events related to


keyboard input or MouseEvent for events related
to mouse input.
 setOn Event

We can use the setOnXXX methods to register event


handlers as the following format:
setOnEvent-type(EventHandler<? super event-
class> value)
 for example,
Key Event

 setOnKeyPressed and setOnKeyReleased


can register key event handlers.
Mouse Events

 We can use setOnMouseEntered,


setOnMouseExited, and
setOnMousePressed to register mouse
event handlers.
Gesture and Touch Events
 JavaFX can handle events from Touch-
Enabled Devices for touches and gestures.
Gesture Description
Triggered when using two-finger to rotate objects. It fires the
following event
Rotate •ROTATION_STARTED
•ROTATE
•ROTATION_FINISHED
Sliding movement. If a mouse wheel is used for scrolling, only
the events of type SCROLL are generated. It fires the following
events:
Scroll
•SCROLL_STARTED
•SCROLL
•SCROLL_FINISHED
•Sweeping movement across the screen. It fires the following
events: SWIPE_LEFT
Swipe •SWIPE_RIGHT
•SWIPE_UP
•SWIPE_DOWN
•Zoom by two-finger. It fires the following events:
ZOOM_STARTED
Zoom
•ZOOM
e.g. rotate and scroll
e.g. Swipe and zoom
e.g. Touch screen
Drag drop
what is the difference between
Event-type and Event-Class?
Theme
 JavaFX application support theme through CSS settings.
 Theming can transforming an entire application's appearance

without changing its functionality.


 In JavaFX you have the ability to create, modify, or use existing

themes to skin your applications.


Application Theme
 The setUserAgentStylesheet(String URL) method accepts a valid

URL string representing the JavaFX CSS file.


 CSS files are bundled inside a jar application or they can reside

on the local file system or a remote web server.


 The setUserAgentStylesheet() method applies styling globally

to all scenes owned by an application.


 To load the CSS file from the classpath, call

getClass().getResource("path/some_file.css").toExternalF
orm() method. It will find the CSS file and produce a URL
String.
 The [Link] file and Java class are in the same directory, so
JavaFX WebEngine

 JavaFX provides capabilities to interoperate with


HTML5 content.
 The underlying web page-rendering engine in
JavaFX is the popular open-source API called
WebKit. This API is used in Apple's Safari browsers,
Amazon's Kindle devices, and was used in
Google's Chrome browser.
 The embedded browser enables you to perform
the following tasks in your JavaFX applications:
 Render HTML from local or remote URLs
 Obtain Web history
 Execute JavaScript commands
 Calls JavaFX from JavaScript

WebEngine

 JavaFX provides a non-GUI component capable of


loading HTML5 content, called the WebEngine
API ([Link]).
 This API is basically an object instance of the
WebEngine class to be used to load a file
containing HTML5 content.
 The HTML5 file to be loaded can be located on a
local file system, a web server, or inside a JAR
file.
 When you load a file using a web engine object,
a background thread is used to load web content
so that it does not block the JavaFX application
thread.
Load from URL
We can load web content from a URL by using
WebEngine's load( ) method.
 The WebEngine uses background threads, adheres to

an event-based programming model.


 A web engine can load web content asynchronously

from a remote web server and notify handler code


when the content is finished loading.
 The this code loads HTML content from a remote

web server in a background worker thread.


To monitor or determine whether
the worker thread has finished a
[Link]
is added to the state property.
Raw HTML5 Content via the
JavaScript Bridge
 JavaFX's WebEngine API has a JavaScript bridge
that allows Java code to invoke JavaScript
functions or script code inside HTML5 content.
 To obtain the raw HTML5 you will need to
interact with the JavaScript bridge to access the
web content's DOM using the web engine's
executeScript() method.
 The following code accesses the HTML
document (DOM) to obtain the raw content
from the [Link]:
Communicating from Java to
JavaScript

 The following code shows how to call


JavaScript function from Java code.
 Suppose we have a web page which has
the following JavaScript Function

 We can call the function from Java code


[Link]("sayHello('Hi
there');");
Communicating from JavaScript to
Java

 JavaFX allows JavaScript code to make calls


into Java code.
JavaFX WebView

 JavaFX provides a GUI WebView


([Link]) node to render
HTML5 content onto the Scene graph.
 A WebView node is a mini-browser.
 We can use the following code to load a
web page and display it.
WebEvents

 JavaFX Web APIs also adhere to an event-driven


programming model.
 The following JavaScript in a web page will pop

up an alert dialog box with a message from


the browser window.
<script> alert('JavaFX is Awesome'); </script>
 When the code is executed inside a JavaFX

WebView node, a native dialog window will not pop


up. However the OnAlert event gets raised as a
[Link] object.
 We can handle those events. To set up the handler,

use the setOnAlert() method with an inbound


parameter of type WebEvent.
WebEvents…


In the event handler we can decide if to show
a dialog.
 The following table shows the events and

actions to trigger them from


Set On Method On Method Property Description
[Link] WebEvents and
Handle JavaScript alert
setOnAlert()
Properties. onAlertProperty() method
WebEngine error
setOnError() onErrorProperty()
handler
JavaScript resize
setOnResized() onResizedProperty()
handler
setOnStatusChanged( JavaScript status
onStatusChanged()
) handler
setOnVisibilityChange onVisibilityChangedProper JavaScript window
d() ty() visibility handler
JavaScript Confirm
Using WebView to display HTML
Using CSS to change WebView
background

You might also like