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

Introduction to JavaFX GUI Programming

The document discusses the transition from console applications to GUI applications using Java, specifically focusing on JavaFX as the modern library for building Rich Internet Applications. It highlights the features and advantages of JavaFX over previous libraries like AWT and Swing, emphasizing its versatility and ability to create user-friendly interfaces. Additionally, it covers the structure of JavaFX applications, including stages, scenes, and layout panes, along with examples of how to implement them.

Uploaded by

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

Introduction to JavaFX GUI Programming

The document discusses the transition from console applications to GUI applications using Java, specifically focusing on JavaFX as the modern library for building Rich Internet Applications. It highlights the features and advantages of JavaFX over previous libraries like AWT and Swing, emphasizing its versatility and ability to create user-friendly interfaces. Additionally, it covers the structure of JavaFX applications, including stages, scenes, and layout panes, along with examples of how to implement them.

Uploaded by

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

GUI

By Muluken W.

1
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
2
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
3
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 4
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.
5
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?
 Nobody knows; probably many years
6
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.
7
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.

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

In addition to these, the developers can also access the
existing features of a Java library such as Swings.
9
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 drag and drop


design interface, which is used to develop FXML
applications (just like Swing Drag & Drop and
DreamWeaver Applications).
10
… 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 holds a

set of classes for canvas, using which we can draw


directly within an area of the JavaFX scene.
 JavaFX also provides classes for Printing purposes in

the package [Link].

11
… 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.
 When used with a supported Graphic Card or GPU it offers

smooth graphics. In case the system does not support


graphic card (hardware) then prism defaults to the software
render path to process the graphics.

12
… 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.

13
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.
7. [Link] − This package provides classes and interfaces to
support the scene graph.

14
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, Grid Pane,

Flow Pane, etc.


 Media elements − such as audio, video and image objects.

 In general, a collection of nodes makes a scene graph.

15
… 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.
 A Canvas class is basically a Node subclass which provides an
API to draw shapes using a set of graphics commands.
 The advantage of Canvas is that we can obtain its
GraphicsContext and invoke drawing operations to render
custom shapes onscreen.
16
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.

17
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 functionality in JavaFX.
It is provided in the form of three components, which
are − •MP3
Audio •WAV
•AIFF

 Media Object − This represents a media file •FLV


Video
 Media Player − To play media content.
 Media View − To display media.
18
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
19
public class MyProgram
{
// Body of class
}

Becomes:

import [Link];

public class MyProgram extends Application
{
// Body of class
}

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

// Override the start method in the Application class • Starting Point of a


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

22
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 stage
[Link]("Second Stage"); // Set the stage title
// Set a scene with a button in the stage
[Link](new Scene(new Button("New Stage"), 100,
100));
[Link](); // Display the stage
}} 23
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)

24
 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.
25
Panes can even contain other panes:

26
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…
27
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
VBox Places nodes in a single (vertical) column 28
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… 29
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
}
30
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("First Name:"),
new TextField(), new Label("MI:")); will have an 11-pixel
TextField tfMi = new TextField(); gap between the top
[Link](1); of the pane and the
[Link]().addAll(tfMi, new Label("Last firstName:"),
row, a 12-pixel
new TextField()); gap between the right-
most node and the
// Create a scene and place it in the stage right side of the pane,
Scene scene = new Scene(pane, 200, 250); 13 pixels at the
[Link]("ShowFlowPane"); // Set bottom, and 14
the stage pixels
title
[Link](scene); on the
// Put scene left side.
in stage
[Link](); // Display theThe Hgap and Vgap
stage
} properties specify the
gap between elements31
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).
TextField nodes typically
// Place nodes in the pane
have a corresponding
[Link]().addAll(new Label("First Name:"), Label,
new TextField(), new so the user can tell what’s
Label("MI:"));
TextField tfMi = new TextField(); supposed to go IN the
[Link](1); TextField
[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 32
FlowPane …
public void start(Stage primaryStage) Finally, we go back to the
{
task of adding the (narrow)
// Create a pane and set its properties
FlowPane pane = new FlowPane(); Middle Initial TextField, plus a
[Link](new Insets(11, 12,Label
13, 14));
and a TextField for the
[Link](5);
[Link](5);
last name to the pane.
Now we have Label /
// Place nodes in the pane TextField pairs for First Name,
[Link]().addAll(new Label("First Name:"),
Middle Initial (a one-
new TextField(), new Label("MI:"));
TextField tfMi = new TextField(); character-wide TextField),
[Link](1); and Last Name
[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
}
33
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.
34
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

35
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)

36
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)

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

38
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

39
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,
A buttonwhereas radio that
is a control
buttons
triggers display
an action a circle
event A CheckBox is used for the
that
whenisclicked.
either filled
JavaFX(if user to make a selection. Like
selected) or blankbuttons,
(if not Button, CheckBox inherits all
provides regular the properties such as
selected).
toggle buttons, check box onAction, text, graphic,
buttons, and radio buttons. alignment, graphicTextGap,
The common features of textFill, contentDisplay from40
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 41
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.

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

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

44
Datepicker

45
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, weanuseImage 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

46
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]();
}
47
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.

48
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
[Link](); }

49
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)
50
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
51
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)

52
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)

53
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)

54
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)

55
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

56
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)

57
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 58
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 properties for viewing the media.
59
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.

60
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

WindowEvent

WorkerStateEvent

WebEvent

61
Events…
 You can define your own event by extending the
Event class.
 The following table lists properties from Event
Property Description
Type of event that occurred. For example, mouse
type
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
 KEY_TYPED
62
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,

[Link](new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
[Link]("Hello World"); } });

63
Key Event

 setOnKeyPressed and setOnKeyReleased


can register key event handlers.

64
Mouse Events

 We can use setOnMouseEntered,


setOnMouseExited, and
setOnMousePressed to register mouse
event handlers.

65
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 66
e.g. rotate and scroll

67
e.g. Swipe and zoom

68
e.g. Touch screen

69
Drag drop

70
71
what is the difference between
Event-type and Event-Class?

72
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").toExternalForm()
method. It will find the CSS file and produce a URL String.
 The [Link] file and Java class are in the same directory, so there
is no need for a path in front of the file name.
73
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
 Manage web pop-up windows

74
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.
75
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.
76
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]:

77
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');");
78
Communicating from JavaScript to
Java

 JavaFX allows JavaScript code to make calls


into Java code.

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

80
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.
81
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() onAlertProperty()
Properties. 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 82
Using WebView to display HTML

83
Using CSS to change WebView
background

84

You might also like