[Go to site: main page, start]

0% found this document useful (0 votes)
13 views63 pages

JavaFX: A Modern GUI Framework

This document provides an overview of Java GUI development using JavaFX, detailing its architecture, components, and features. It compares JavaFX with previous technologies like AWT and Swing, highlighting JavaFX's advantages such as lightweight design and cross-platform capabilities. Additionally, it outlines the setup process for JavaFX applications and lists commonly used UI controls.

Uploaded by

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

JavaFX: A Modern GUI Framework

This document provides an overview of Java GUI development using JavaFX, detailing its architecture, components, and features. It compares JavaFX with previous technologies like AWT and Swing, highlighting JavaFX's advantages such as lightweight design and cross-platform capabilities. Additionally, it outlines the setup process for JavaFX applications and lists commonly used UI controls.

Uploaded by

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

Wolaita Sodo University

School of Informatics
Department of Computer Science
Chapter Three
Java GUI using JAVAFX

Compiled by Dawit Uta. (M. Tech.)


Computer Science Department, WSU
website address: [Link]
2 Course outline
Chapter 3: Java GUI using JAVAFX
3.1. JAVAFX architecture and Program structure
3.2. JAVAFX layout components
3.3. Basic UI controls
3.3.1. Event handlers
3.3.1. UI controls
3.4. Composite UI controls
3.5. Shapes
3.5.1. Color, Texts, Fonts
3.5.2. Lines, Circle, Rectangle
3.5.3. CSS styling
3.6. Properties and Bindings
3.7. Graphics and Animation
3
Introduction to GUI
 Many Java application use a graphical user interface or GUI (pronounced “gooey).

 A GUI is a graphical window or windows that provide interaction with the user.

 GUI’s accept input from:

– the keyboard

– a mouse.

 A window in a GUI consists of components that:

– present data to the user, allow interaction with the application.

 The JavaFX is a set of Java libraries designed to enable developers to create and deploy rich
client applications that behave consistently across platforms.
Introduction to GUI ….
4 GUI components

 .
5
Introduction to GUI ….

Java programmers use the Java Foundation Classes (JFC) to create GUI
applications.
The JFC consists of several sets of classes
The two sets of JFC classes that we focus on are AWT and Swing classes.
Java is equipped with a set of classes for drawing graphics and creating
graphical user interfaces.
These classes are part of the Abstract Windowing Toolkit (AWT).
The AWT allows creation of applications and applets with GUI
components.
The AWT does not actually draw user interface components on the screen.
6 AWT
Some common AWT GUI components are:
– buttons, labels, text fields, check boxes, radio buttons, combo boxes,
and sliders.
7
AWT
 The AWT communicates with a layer of software, peer classes.
 Each version of Java for a particular operating system has its own set of peer classes.
 The AWT is roughly broken into three categories
 Components
 Layout Managers
 Graphics
 Many AWT components have been replaced by Swing components
 Java programs using the AWT:
 look consistent with other applications on the same system.
 can offer only components that are common to all the operating systems that support
Java.
 The behavior of components across various operating systems can differ.
8 Swing

Same concepts as AWT


 Doesn’t work in ancient Java implementations (Java 1.1 and earlier)
 Many more controls, and they are more flexible
 Some controls, but not all, are a lot more complicated
 Gives a choice of “look and feel” packages
 Much easier to build an attractive GUI
Swing
9

Containers
 Contain and manage other components
 Top Level/Internal
 Examples: JFrame (Top Level), JScrollPane, Jpanel
Basic Controls
 Atomic components
 Used for showing output and/or getting some input
 Inherits Jcomponent
 Examples: JButton, JLabel, JTextArea, JTable, Jlist
 Usually every Swing class extends the corresponding AWT class
 For backward-compatibility reasons
Swing Components
10
AWT vs. Swing
11

Programmers cannot easily extend the AWT components.


AWT components are commonly called heavyweight components.
Swing was introduced with the release of Java 2.
Swing is a library of classes that provide an improved alternative for
creating GUI applications and applets.
Very few Swing classes rely on peer classes, so they are referred to
called lightweight components.
Swing draws most of its own components.
Swing components have a consistent look and predictable behavior on
any operating system.
Swing components can be easily extended.
12 AWT vs. Swing
Some of the AWT classes are used to determine when events, such as
the clicking of a mouse, take place in applications.
 In an application that uses an AWT class, it is necessary to use the
following import statement.
import [Link].*;
Note that there is no x after java in this package name.
 In an application that uses Swing classes, it is necessary to use the
following import statement:
import [Link].*;
Note the letter x that appears after the word java.
13 AWT Vs. Swing
Swing is bigger, slower, and more complicated
 But not as slow as it used to be
 Swing is more flexible and better looking
 Swing and AWT are incompatible--you can use either, but you can’t
mix them
 Actually, you can, but it’s tricky and not worth doing
 Learning the AWT is a good start on learning Swing
 Many of the most common controls are just renamed
AWT: import [Link].*;
AWT: Button b = new Button ("OK");
Swing: import [Link].*;
Swing: JButton b = new JButton("OK");
What is JavaFX?
14
 JavaFX is a Java library used to develop Desktop applications as well as Rich Internet
Applications (RIA).

 The applications built in JavaFX, can run on multiple platforms including Web, Mobile and
Desktops.

 JavaFX is intended to replace swing in Java applications as a GUI framework. However, It


provides more functionalities than swing.

 Like Swing, JavaFX also provides its own components and doesn't depend upon the
operating system. It is lightweight and hardware accelerated.

 It supports various operating systems including Windows, Linux and Mac OS.
JavaFX Basic Concepts
15
 In general, the JavaFX framework has all of the good features of Swing. For example,
JavaFX is lightweight. It can also support an MVC architecture. Much of what you already
know about creating GUIs using Swing is conceptually applicable to JavaFX. That said,
there are significant differences between the two.

 From a programmer’s point of view, the first differences you notice between JavaFX and
Swing are the organization of the framework and the relationship of the main components.

 Simply put, JavaFX offers a more streamlined, easier-to-use, updated approach.

 JavaFX also greatly simplifies the rendering of objects because it handles repainting
automatically. It is no longer necessary for your program to handle this task manually.
JavaFX Basic Concepts cont…
16
 The preceding is not intended to imply that Swing is poorly designed. It is not. It is just that
the art and science of programming has moved forward, and JavaFX has received the
benefits of that evolution.

 Simply put, JavaFX facilitates a more visually dynamic approach to GUIs.

 JavaFX elements are contained in packages that begin with the javafx prefix. There are
more than 30 JavaFX packages in its API library. Here are some examples of packages:
[Link], [Link], [Link], and [Link].

 Although we will only use a few of these packages in this chapter, you will want to spend
some time browsing their capabilities. JavaFX offers a wide array of functionality.
JAVAFX architecture and Program structure
17
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
[Link]: Contains classes to add transition based animations such as fill, fade, rotate,
scale and translation, to the JavaFX nodes.
[Link]: Contains a set of classes responsible for the JavaFX application life cycle.
[Link]: Contains classes to add CSS–like styling to JavaFX GUI applications.
[Link]: Contains classes and interfaces to deliver and handle JavaFX events.
[Link]: Contains classes to define 2D objects and perform operations on them.
[Link]:- This package holds the top level container classes for JavaFX application.
[Link]:- This package provides classes and interfaces to support the scene graph.
 In addition, it also provides sub-packages such as canvas, chart, control, effect, image, input,
layout, media, paint, shape, text, transform, web, etc. There are several components that
support this rich API of JavaFX.
JAVAFX architecture and Program structure
18

Figure 1

Scene Graph
 The JavaFX scene graph, shown as part of the top layer in Figure 1, is the starting point for
constructing a JavaFX application. It is a hierarchical tree of nodes that represents all of the
visual elements of the application's user interface. It can handle input and can be rendered.
JAVAFX architecture and Program structure
19

 To develop GUI Applications using Java programming language, the programmers rely on
libraries such as Advanced Windowing Tool kit and Swing. After the advent of JavaFX,
these Java programmers can now develop GUI applications effectively with rich content.

 The applications developed using JavaFX can run on various devices such as Desktop
Computers, Mobile Phones, TVs, Tablets, etc..

History of JavaFX
 JavaFX was developed by Chris Oliver. Initially the project was named as Form Follows
Functions (F3) .

 It is intended to provide the richer functionalities for the GUI application development.
Later, Sun Micro-systems acquired F3 project as JavaFX in June, 2005
JAVAFX architecture and Program structure
20

 Sun Micro-systems announces it officially in 2007 at W3 Conference. In October 2008,


JavaFX 1.0 was released.

 In 2009, ORACLE corporation acquires Sun Micro-Systems and released JavaFX 1.2. the
latest version of JavaFX is JavaFX 1.8 which was released on 18th March 2014.
Features of JavaFX
Feature Description
Java Library It is a Java library which consists of many classes and interfaces that are written
in Java.
FXML FXML is the XML based Declarative mark up language. The coding can be
done in FXML to provide the more enhanced GUI to the user.
Features of JavaFX
21

Scene Builder Scene Builder generates FXML mark-up which can be ported to an IDE.

Web view Web pages can be embedded with JavaFX applications. Web View uses
WebKitHTML technology to embed web pages.
Built in UI JavaFX contains Built-in components which are not dependent on operating
controls system. The UI component are just enough to develop a full featured
application.
CSS like styling JavaFX code can be embedded with the CSS to improve the style of the
application. We can enhance the view of our application with the simple
knowledge of CSS.
Swing The JavaFX applications can be embedded with swing code using the Swing
interoperability Node class. We can update the existing swing application with the powerful
features of JavaFX.
Features of JavaFX
22
Canvas API Canvas API provides the methods for drawing directly in an area of a
JavaFX scene.
Rich Set of APIs JavaFX provides a rich set of API's to develop GUI applications.
Integrated Graphics An integrated set of classes are provided to deal with 2D and 3D graphics.
Library
Graphics Pipeline JavaFX graphics are based on Graphics rendered pipeline(prism). It offers
smooth graphics which are hardware accelerated.
High Performance The media pipeline supports the playback of web multimedia on a low
Media Engine latency. It is based on a Gstreamer Multimedia framework.
Self-contained Self Contained application packages have all of the application resources
application and a private copy of Java and JavaFX Runtime.
deployment model
JavaFX UI Controls
23
 Every graphical user interface of every desktop application mainly considers three main aspects UI
elements, layouts and behavior.

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

 Behavior:- These are events which occur when the user interacts with UI elements.

 JavaFX provides several classes in the package [Link]. To create various GUI
components (controls), JavaFX supports several controls such as label, button, text field, etc.

 Each control is represented by a class; you can create a control by instantiating its respective class.
24 The Stage and Scene Classes
 The central metaphor implemented by JavaFX is the stage. As in the case of an actual
stage play, a stage contains a scene.
 Thus, loosely speaking, a stage defines a space and a scene defines what goes in that
space. Or, put another way, a stage is a container for scenes and a scene is a container for
the items that comprise the scene.
 As a result, all JavaFX applications have at least one stage and one scene. These elements
are encapsulated in the JavaFX API by the Stage and Scene classes.
 To create a JavaFX application, you will, at minimum, add at least one Scene object to a
Stage. Let’s look a bit more closely at these two classes.
 Stage is a top-level container. All JavaFX applications automatically have access to one
Stage, called the primary stage. The primary stage is supplied by the run-time system
when a JavaFX application is started. Although you can create other stages, for many
applications, the primary stage will be the only one required.
JavaFX UI Controls cont…
25
Following are the lists of commonly used controls while the GUI is designed using JavaFX

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 Menu JavaFX provides a Menu class to implement menus. Menu is the main
component of any application.
JavaFX UI Controls cont…
26
6 TextField Text Field is basically used to get the input from the user in the form of text.

[Link] represents TextField
7 PasswordField PasswordField is used to get the user's password. Whatever is typed in the
passwordfield is not shown on the screen to anyone.
8 HyperLink HyperLink are used to refer any of the webpage through your appication. It
is represented by the class [Link]
9 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.
10 ProgressBar Progress Bar is used to show the work progress to the user. It is represented
by the class [Link].
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.
JavaFX – Environment setup
27
 From Java8 onwards, the JDK (Java Development Kit) includes JavaFX library in it.
Therefore, to run JavaFX applications, you simply need to install Java8 or later version in
your system.
 Visit the JavaSE Downloads Page, click on the JDK Download button and install it.
 In addition to it, IDE’s like Eclipse and NetBeans provide support for JavaFX.
 NetBeans provides inbuilt support for JavaFX. On installing this, you can create a JavaFX
application without any additional plugins or JAR files.
 Visit the NetBeans website and click the Download button in order to download the
NetBeans software and install it.
Setting up the Path for Windows
28

 After installing Java, you need to set the path variables. Assume that you have installed
Java in C:\Program Files\java\jdk1.8.0_91directory.

 Now you can follow the steps that are given below

 Right-click on 'My Computer' and select 'Properties'.

 Click on the 'Environment Variables' button under the 'Advanced' tab.

 Now, alter the 'Path' variable so that it also contains the path to the Java executable. For
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path
to read 'C:\WINDOWS\SYSTEM32; C:\Program Files\java\ jdk1.8.0_91\bin'.
Setting up the Path for Windows …
29
JavaFX Application Structure
30 In general, a JavaFX application will have three major components namely Stage,
Scene and Nodes as shown in the following diagram.
Stage
 A stage (a window) contains all the objects of a JavaFX
application. It is represented by Stage class of the
package [Link]. The primary stage is created by the
platform itself.
 The created stage object is passed as an argument to
the start() method of the Application class.
 A stage has two parameters determining its position
namely Width and Height.
 You have to call the show() method to display the contents
of a stage.
 Scene represents the physical contents of a JavaFX
application. It contains all the contents of a scene graph.
Creating a JavaFX Application
31
 To create a JavaFX application, you need to instantiate the Application class and implement
its abstract method start()
 In this method, we will write the code for the JavaFX Application.
 Application Class
 The Application class of the package [Link] is the entry point of the application
in JavaFX.
 In the main method, you have to launch the application using the launch() method. This
method internally calls the start() method of the Application class as shown in the following
program. public class JavafxSample extends Application {
@Override public void start(Stage primaryStage) throws Exception {
/* Code for JavaFX application. (Stage, scene, scene graph) */ }
public static void main(String args[]){
launch(args); }
}
Creating JavaFx application using Netbeans IDE
32
 After installing Netbeans and JDK tool, open Netbeans then click the file menu, select New
Project… to open the New project wizard as shown in the following screenshot.
Creating JavaFx application using Netbeans IDE
33 …New Project wizard, select JavaFX and click on Next. It starts creating a
In the
new JavaFX Application for you.
Creating JavaFx application using Netbeans IDE
34 …the name of the project and location of the project in the NewJavaFX
Select
Application window and then click Finish. It creates a sample application with
the given name.
Creating JavaFx application using Netbeans IDE
35 …instance, an application with a name javafxsample is created. Within this application, the
In this
NetBeans IDE will generate a Java program with the name [Link]. As shown in the following
screenshot, this program will be created inside NetBeans Source Packages → javafxsample.
Creating JavaFx application using Netbeans IDE
36 …
Right-click on the file and select Run File to run this code as shown in the
following screenshot.
Creating JavaFx application using Netbeans IDE
37 …automatically created program contains the code which generates a simple
This
JavaFX window having a button with the label Say ‘Hello World’ in it. Every time you click
on this button, the string Hello World will be displayed on the console as shown below..
Source code
38
package javafxapplication1;
import [Link];
import [Link]; });
import [Link]; StackPane root = new StackPane();
import [Link]; [Link]().add(btn);
import [Link]; Scene scene = new Scene(root, 300, 250);
import [Link]; [Link]("Hello World!");
import [Link]; [Link](scene);
public class javafxsample extends Application { [Link]();
@Override }
public void start(Stage primaryStage) { /**
Button btn = new Button(); * @param args the command line arguments
[Link]("Say 'Hello World '"); */
[Link](new EventHandler<ActionEvent>() { public static void main(String[] args) {
@Override launch(args);
public void handle(ActionEvent event) { }
[Link]("Hello World!"); }
}
Layouts
39
 After constructing all the required nodes in a scene, we will generally arrange them in
order.
 This arrangement of the components within the container is called the Layout of the
container. We can also say that we followed a layout as it includes placing all the
components at a particular position within the container.
 JavaFX provides several predefined layouts such as HBox, VBox, Border Pane, Stack
Pane, Text Flow, Anchor Pane, Title Pane, Grid Pane, Flow Panel, etc.
 Each of the above mentioned layout is represented by a class and all these classes belongs
to the package [Link].
 The class named Pane is the base class of all the layouts in JavaFX.
Layouts
40
 Creating a Layout
 To create a layout, we need to
• Create node
• Instantiate the respective class of the required layout.
• Set the properties of the layout.
• Add all the created nodes to the layout.
 Creating Nodes
 First of all, create the required nodes of the JavaFX application by instantiating their
respective classes.
 For example, if we want to have a text field and two buttons namely, play and stop in a
HBox layout, we will have to initially create those nodes as shown in the following code
block
Layouts
41
 //Creating a text field //Creating the play button
TextField textField = new TextField(); Button playButton = new Button("Play");

//Creating the stop button


Button stopButton = new Button("stop");

Instantiating the Respective Class


After creating the nodes (and completing all the operations on them), instantiate the class of
the required layout.
For Example, if you want to create a Hbox layout, you need to instantiate this class as follows.
HBox hbox = new HBox();
Layouts
42

 Setting the Properties of the Layout


 After instantiating the class, you need to set the properties of the layout using their
respective setter methods.
 For example − If you want to set space between the created nodes in the HBox layout, then
you need to set value to the property named spacing. This can be done by using the setter
method setSpacing() as shown below
 [Link](10);
 Adding the Shape Object to the Group
 Finally, you need to add the object of the shape to the group by passing it as a parameter of
the constructor as shown below.
 Creating a Group object
Group root = new Group(line);
Layouts
43

[Link] Shape & Description


1 Hbox The HBox layout arranges all the nodes in our application in a single horizontal row.
The class named HBox of the package [Link] represents the text horizontal box layout.
2 Vbox The 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.
3 BorderPane The Border Pane layout arranges the nodes in our application in top, left, right, bottom and
center positions.
The class named BorderPane of the package [Link] represents the border pane layout.
4 StackPane The stack pane layout arranges the nodes in our application on top of another just like in a
stack. The node added first is placed at the bottom of the stack and the next node is placed on top of it.
The class named StackPane of the package [Link] represents the stack pane layout.
5 TextFlow The Text Flow layout arranges multiple text nodes in a single flow.
The class named TextFlow of the package [Link] represents the text flow layout.
JavaFX Event handlers
44

 In JavaFX applications, events are notifications that something has happened. For example,
clicking on a button, pressing a keys, 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. Event Handling is the mechanism that controls the event and decides what
should happen, if an event occurs.

 Registered event filters and event handlers within the application receive the event and
provide a response.
Types of Events: The events can be broadly classified into the following two categories
Foreground Events: events which require the direct interaction of a user. They are generated
as consequences of a person interacting with the graphical components in a GUI.
JavaFX Event handlers
45

 For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page, etc.

 Background Events: events that don't require the interaction of end-user are known as
background events. The operating system interruptions, hardware or software failure, timer
expiry, operation completion are the example of background events.

 JavaFX provides support to handle a wide varieties of events. The class named Event of
the package [Link] is the base class for an event.
JavaFX Event handlers
46
 JavaFX provides a wide variety of events. Some of them are listed below.
 Mouse Event − This is an input event that occurs when a mouse is clicked. It is represented
by the class named MouseEvent. It includes actions like mouse clicked, mouse pressed,
mouse released, mouse moved, mouse entered target, mouse exited target, etc.
 Key Event − This is an input event that indicates the key stroke occurred on a node. It is
represented by the class named KeyEvent. This event includes actions like key pressed,
key released and key typed.
 Drag Event − This is an input event which occurs when the mouse is dragged. It is
represented by the class named DragEvent. It includes actions like drag entered, drag
dropped, drag entered target, drag exited target, drag over, etc.
 Window Event − This is an event related to window showing/hiding actions. It is
represented by the class named WindowEvent. It includes actions like window hiding,
window shown, window hidden, window showing, etc.
47
 JavaFX provides handlers and filters to handle events. In JavaFX every event has:-
 Target: The node on which an event occurred. A target can be a window, scene, and a node.
 Source: The source from which the event is generated will be the source of the event. In the
above scenario, mouse is the source of the event.
 Type: Type of the occurred event; in case of mouse event – mouse pressed, mouse released
are the type of events.
 Assume that we have an application which has a Circle, Stop and Play Buttons inserted
using a group object as follows

 If you click on the play button, the source will be the


mouse, the target node will be the play button and the
type of the event generated is the mouse click.
48
Event types are hierarchical. Every event type has a name and a super type. For example, the
name of the event for a key being pressed is KEY_PRESSED, and the super type
is [Link]. The super type of the top-level event type is null. Figure below shows a
subset of the hierarchy. Event Type Hierarchy
Event Handlers
49
 Event handlers contains application logic to process an event. A node can be registered to
more than one Event
 The interface [Link] must be implemented by all the event handlers
Using Convenience Methods for Event Handling
 JavaFX provides the convenience methods which can be used to handle events within our
JavaFX application. They provide an easy way to create and register event handlers to
respond to KeyEvent, MouseEvent, Action Event, Drag & Drop Events and many more.
 Node class contains various Event Handler properties which can be set to the User defined
Event Handlers using the setter methods defined in the class.
 Setting, EventHandler properties of the Node class, to the user defined event handlers,
automatically registers the handlers to receive the corresponding event types.
50
 Convenience methods for the event handlers registration has the format like
setOnEvent-type(EventHandler<? super event-class> value)
 where the Event type is the type of the event that is to be handled through the defined
functions, for example, setOnMouseMoved() will be the convenience method to
register the event handler for the event Mouse_Moved.
 For example, to add a mouse event listener to a button, you can use the convenience
method setOnMouseClicked() as shown below.
JavaFX Shapes
51
 JavaFX allows to draw several 2D & 3D shapes. a 2D shape is a geometrical figure that can
be drawn on the XY plane, these include Line, Rectangle, Circle, etc.
 Using the JavaFX library, we can draw :-
 Predefined shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve,
Quad Curve, Arc.
 Path elements such as MoveTO Path Element, Line, Horizontal Line, Vertical Line, Cubic
Curve, Quadratic Curve, Arc.
 Each of the above mentioned 2D shape is represented by a class and all these classes belongs
to the package [Link].
 The class named Shape is the base class of all the 2 -Dimensional shapes in JavaFX
Creating a 2D Shape
52
 To create a chart, you need to
 Instantiate the respective class of the required shape.
 Set the properties of the shape.
 Add the shape object to the group.
Instantiating the Respective Class
 To create a 2 Dimensional shape, first of all you need to instantiate its respective class.
 For example, if you want to create a line you need to instantiate the class named Line as
follows
Line line = new Line();
Setting the Properties of the Shape
53
 After instantiating the class, you need to set the properties for the shape using the setter
methods.
 For example, to draw a line you need to pass its x and y coordinates of the start point and
end point of the line. You can specify these values using their respective setter methods as
follows
Adding the Shape Object to the Group
 //Setting the Properties of the Line  Finally, you need to add the object of the
[Link](150.0f); shape to the group by passing it as a
parameter of the constructor as shown below.
[Link](140.0f);
//Creating a Group object
[Link](450.0f); Group root = new Group(line);
[Link](140.0f);
Drawing More Shapes Through Path Class
54
 To draw such complex structures JavaFX provides a class named Path. This class represents
the geometrical outline of a shape.
 It is attached to an observable list which holds various Path Elements such as moveTo,
LineTo, HlineTo, VlineTo, ArcTo, QuadCurveTo, CubicCurveTo.
 On instantiating, this class constructs a path based on the given path elements. You can pass
the path elements to this class while instantiating it as follows
Path myshape = new Path(pathElement1, pathElement2, pathElement3);
 Or, you can get the observable list and add all the path elements using addAll() method as
follows Path myshape = new Path();
[Link]().addAll(pathElement1, pathElement2, pathElement3);
 You can also add elements individually using the add() method as
Path myshape = new Path();
[Link]().add(pathElement1);
The Move to Path Element
55
 The Path Element MoveTo is used to move the current position of the path to a specified
point. It is generally used to set the starting point of a shape drawn using the path elements.
 It is represented by a class named LineTo of the package [Link]. It has 2
properties of the double data type namely
 X − The x coordinate of the point to which a line is to be drawn from the current position.
 Y − The y coordinate of the point to which a line is to be drawn from the current position.
 You can create a move to path element by instantiating the MoveTo class and passing the x,
y coordinates of the new point as follows
 MoveTo moveTo = new MoveTo(x, y);
Example: Drawing a Complex Path
56
 This example shows how to draw the following shape using the Path, MoveTo and Line
classes
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ComplexShape extends
Application {
@Override
public void start(Stage stage) {
//Creating a Path
Path path = new Path();
[Link]().addAll(line1, line2, line3,
57
line4, line5);
//Moving to the starting point //Creating a Group object
MoveTo moveTo = new MoveTo(108, 71); Group root = new Group(path);
//Creating 1st line //Creating a scene object
LineTo line1 = new LineTo(321, 161); Scene scene = new Scene(root, 600, 300);
//Creating 2nd line //Setting title to the Stage
LineTo line2 = new LineTo(126,232); [Link]("Drawing an arc through a path");
//Creating 3rd line //Adding scene to the stage
LineTo line3 = new LineTo(232,52); [Link](scene);
//Creating 4th line //Displaying the contents of the stage
LineTo line4 = new LineTo(269, 250); [Link]();
//Creating 4th line }
LineTo line5 = new LineTo(108, 71); public static void main(String args[]){
//Adding all the elements to the path launch(args);
[Link]().add(moveTo); }}
CSS in JavaFX
58
 Cascading Style Sheets, also referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.
 CSS handles the look and feel part of a web page. Using CSS, you can control the color of
the text, style of fonts, spacing between paragraphs, size of columns and layout.
 Apart from these, you can also control the background images or colors that are used, layout
designs, variations in display for different devices and screen sizes as well as a variety of
other effects.
 JavaFX provides the facility of using CSS to enhance the look and feel of the application.
The package [Link] contains the classes that are used to apply CSS for JavaFX
applications.
 A CSS comprises of style rules that are interpreted by the browser and then applied to the
corresponding elements in your document.
CSS in JavaFX
59
 A style rule is made of three parts, which are −
 Selector − A selector is an HTML tag at which a style will be applied. This could be any
tag like <h1> or <table>, etc.
 Property − A property is a type of attribute of the HTML tag. In simpler terms, all the
HTML attributes are converted into CSS properties. They could be color, border, etc.
 Value − Values are assigned to properties. For example, a color property can have value
either red or #F1F1F1, etc. You can put CSS Style Rule Syntax as follows −

 The default style sheet used by


JavaFX is [Link].
 It is found in the JavaFX runtime jar.
CSS in JavaFX
60
 Adding Your own Style Sheet
 You can add your own style sheet to a scene in JavaFX as follows

 Adding Inline Style Sheets


 You can also add in-line styles using the setStyle() method. These styles consist of only
key-value pairs and they are applicable to the nodes on which they are set. Following is a
sample code of setting an inline style sheet to a button.
CSS in JavaFX
61
 Consider the JavaFX application which displays a form with a Text Field, Password Field,
Two Buttons. By default, this form looks as shown in the following screenshot

The following program is an example which demonstrates


how to add styles to the above application in JavaFX.
import [Link];
import static [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JavaFXCssExample extends Application {
62
@Override //Setting the vertical & horizontal gaps b/n the columns
public void start(Stage stage) { [Link](5);
//creating label email [Link](5);
Text text1 = new Text("Email"); //Setting the Grid alignment
//creating label password [Link]([Link]);
Text text2 = new Text("Password"); //Arranging all the nodes in the grid
//Creating Text Filed for email [Link](text1, 0, 0);
TextField textField1 = new TextField(); [Link](textField1, 1, 0);
//Creating Text Filed for password [Link](text2, 0, 1);
PasswordField textField2 = new PasswordField(); [Link](textField2, 1, 1);
//Creating Buttons [Link](button1, 0, 2);
Button button1 = new Button("Submit"); [Link](button2, 1, 2);
Button button2 = new Button("Clear"); //Styling nodes
//Creating a Grid Pane [Link]("-fx-background-color:
GridPane gridPane = new GridPane(); darkslateblue; -fx-text-fill: white;");
//Setting size for the pane [Link]("-fx-background-color:
[Link](400, 200); darkslateblue; -fx-text-fill: white;");
//Setting the padding
[Link](new Insets(10, 10, 10, 10));
63

[Link]("-fx-font: normal bold 20px 'serif' ");


[Link]("-fx-font: normal bold 20px 'serif' ");
[Link]("-fx-background-color: BEIGE;");
// Creating a scene object
Scene scene = new Scene(gridPane);
// Setting title to the Stage
[Link](“JavaFX CSS Example");
// Adding scene to the stage
[Link](scene);
//Displaying the contents of the stage
[Link](); }
public static void main(String args[]){
launch(args);
} }
The End of Chapter 3

You might also like