Unit 1
Unit 1
Structure
1.0 Introduction
1.1 Objectives
1.2 Introduction to AWT, Swing and JavaFX
1.2.1 Abstract Window Toolkit (AWT)
1.2.2 Swing
1.2.3. JavaFX
1.3 Features of JavaFX
1.4 User Interface Components of JavaFX
1.5 Work with Layouts
1.6 Add HTML Content
1.7 Add Text and Text Effects in JavaFX
1.8 Summary
1.9 Solutions/ Answer to Check Your Progress
1.10 References/Further Reading
1.0 INTRODUCTION
Graphical User Interface (GUI) is a kind of interface through which users can interact
with computer applications. Be it web applications, mobile apps, or other commonly
used applications like online banking or the online railway reservation system, we
look for ease of interaction by using proper buttons, menus, and other controls. These
interfaces use proper GUI components and controls. Earlier engineers or programmers
used to interact with the computer through the DOS prompt/interface using command
line. This interface is also used to be called as the character user interface(CUI),
which was very inconvenient for non-programming users. With the development of
the Graphical user interface, the use of computing devices by non-technical users or
ordinary users has been more convenient because GUI provides an interface that
allows users to interact with electronic devices through graphical objects and controls
to convey information and represent action taken by the users.
Java provides a very rich set of Graphical User interface (GUI) API for developing
GUI programs. In fact, GUI is one of the most helpful features provided by Java
Development Kit (JDK). Java provides various essential classes and libraries for the
implementation of graphic classes to the programmers for constructing their own
Graphical User Interface applications. The Graphic classes developed by the JDK
developer team are highly complex and uses many advanced design patterns.
However, for the programmers, the reuse of these classes and methods are very easy
to use. Some commonly used APIS for Graphic User interface (GUI) programming
are : Applet, AWT, Swing, JavaFX. In this unit, you will learn about the basics of
AWT, Swing and JavaFX API and its implementation with examples.
JavaFX is an open-source programming platform for developing next-generation
client applications to implement mobile apps, desktop systems and embedded
systems built using Java . It is designed using the Model View Controller (MVC)
design pattern to keep the code that handles an application’s data, separate from the
User Interface Code. To develop enterprise applications, generally, MVC design
pattern is used, because it does not mix the UI code with the application logic code.
The controller is the mediator between UI and Business logic (the data). Working with
JavaFX, the model corresponds to an application’s data model, the view is FXML.
The FXML is XML-based language designed to create the user interface for JavaFX
applications. The controller is the code that determines the action when the user
1
Introduction to GUI in
Java interacts with the UI. Mainly the controller handles all events in the application. The
First LTS (long term support) version of JavaFX is the JavaFX 11 which was released
by Gluon. It is recommended to use the current LTS version for applications
development. In this unit JavaFX 11 is used for the demonstration of the examples.
1.1 OBJECTIVES
2
Graphical User Interface
and Java Database
Component Class Connectivity
As we can see in figure 1, the Component class is on the top of the AWT hierarchy. It
is an abstract class that encapsulates all of the attributes of a visual component. It is
platform-dependent i.e., its components are displayed according to the view of the
operating system on which it runs. It is also heavyweight because its components uses
the OS's resources during the execution of the program. User interface elements (i.e.,
textbox, label, list, checkbox, etc.) which are displayed on the screen and used to
interact with the user are subclasses (such as Label, TextField, TextArea,
RadioButton, CheckBox, List, Choice etc.) of Component class.
Container Class
The container is a subclass of Component class of AWT. It provides the additional
methods that allow other Component objects to call within the container object. Other
Container objects can be stored inside a container because they are themselves
instances of the Component class. This makes it a multilevelled containment system.
A container is responsible for laying out or positioning the component’s object using
the various layout managers.
Panel Class
The panel class is the subclass of the container class that implements the container
class only. It does not provide any special new methods. It provides space to assemble
all components, including other panels. Other components can be added within a
Panel object by calling its add() method (which is inherited from Container). Once
these components are assembled or added within the panel, you can set their position
and resize them manually using the setLocation(), setSize(), setPreferredSize(), or
setBounds() methods which are defined by the Component class.
Windows Class
The Window is an area that is displayed on the screen when you execute an AWT
program. It creates a top-level window that is not contained with any other object; it
directly sits on the desktop screen. It provides a multitasking environment for users to
interact with the system through the component shown on the screen. It must have a
frame, dialog or another window defined by the programmer/owner when it is
constructed in the program because window objects can not be created directly.
Frame Class
The Frame is the subclass of Window. It is the top-level of windows that provides title
bar, menu bar, borders and resizing option for window. It can also have other
components like button, text field, scrollbar etc. It encapsulates the window and uses
BorderLayout as the default layout manager. Frame is one of the most widely used
containers for AWT applications.
import Java.awt.*;
import Java.awt.event.WindowAdapter;
import Java.awt.event.WindowEvent;
AWTFirstExample ()
{
3
Introduction to GUI in
Java //Creating a frame
myFrame= new Frame();
//Creating a label
Label myLabel = new Label ("Welcome to First AWT Programme.");
1.2.2 Swing
In section 1.2.1 we learned about AWT in Java, the first GUI API provided by Java
programming lanuage. Swing is another API for developing Windows based
applications in Java. Due to the limitation of AWT (components use native code
resources, heavyweight, platform-dependent, etc.), Swing was introduced in the year
of 1997 which is a platform-independent “model–view–controller” GUI framework
for Java. The components of swing are written in Java which is a part of Java
Foundation Classes (JFC). Swing API in Java not only provides platform
independence but also are lightweight components. JFC consists of Swing, Java2D,
Accessibility, Internationalization and pluggable look and feel support API. The JFC
has been integrated into code Java since JDK1.2.
As mentioned above, Swing is developed on top of the AWT, but it has many
differences. Some significant differences are given in table 2.
4
Graphical User Interface
and Java Database
Connectivity
As explained above, Swing is developed on top of the AWT which overcomes the
limitations of AWT. Two major features of the Swing Components are:
Lightweight
Swing Supports a Pluggable Look and Feel
These features provides an effective and easy-to-use solution to the problems of GUI
development in Java. Both the features of Swing are explained below:
Swing Components Are Lightweight: As we know the Swing has been written in
Java which make it platform-independent and does not map directly to platform-
specific peers. Another reason is that it is lightweight because its components are
rendered using graphics primitives; components can be transparent, which enables
5
Introduction to GUI in
Java non rectangular shapes. That is why the lightweight components are flexible and
more efficient. It determines the look and feel of each component; therefore,
lightweight components do not translate into native peers. This means that each
component of the Swing will work in a consistent manner across all the platforms.
The look and feel of a component is controlled by Swing. It supports Pluggable Look
and Feel because each of the component is rendered by Java code in place of native
peers. It means that it is possible to separate the look and feel of a component from
the logic of the component in Swing. By separating the look and feel, it provides a
significant advantage. It makes it possible to “plug in” a new look and feel for any
given component without having any adverse effects on the code that uses it. Hence, it
becomes possible to define entire sets of look-and-feels that represent different GUI
styles. To use a specific style, programmer need to simply apply “plug-in” in the
design. Once this is done, all components are automatically rendered using that style.
For example, if you are sure that an application is going to run only in a Windows
environment, it is possible to specify the Windows look and feel. Also, through proper
programming, the look and feel can be changed dynamically at run time. But we are
not going to discuss that in this course. Now let us see the example program
developed using Swing in Java
//setting size
setSize(400, 400);
Output:
6
Figure 3: Output screen of above example 2 Graphical User Interface
and Java Database
Connectivity
1.2.3 JavaFX
JavaFX is the most popular set of APIs for GUI development using Java, which is
used to develop Windows-based applications and Rich Internet Applications (RIA)
that can run through a wide variety of devices. JavaFX is the next-generation open-
source client application platform for implementing mobile, desktop, and embedded
systems, which is built on the Java platform. Firstly, it was introduced into JDK1.8,
which intended to replace Swing in Java. An application built on JavaFX can run on
multiple platforms, including Web, Mobile and Desktops. In this unit we will deep
dive into all essential aspects of JavaFX.
Java provides its GUI APIs (e.g., AWT/Swing/JavaFX graphic) with JDK. Also, apart
from this, there are some other GUI tools that work with Java easily, such as Google
Web Toolkit (GWT), which Google provides, and Standard Widget Toolkit (SWT)
provided by Eclipse.
This unit mainly focuses on a practical base session on the latest GUIs APIs called
JavaFX. Prerequisite software/tools/libraries to a setup development environment for
JavaFX:
7
Introduction to GUI in
Java
5. Default project has been created with error because of running JDK 11 and
missing the JavaFX SDK. This error will not generate if you use JDK8, because
JDK 8 provides an inbuilt library of JavaFX. Then you have to configure the
global library. Then you may create a new project of JavaFX running on JDK 11.
6.For fixing the above error and setting up JavaFX Library in the Project, first we
click right-click on the project and select open module settings as shown in
figure no 8 .
7. Firstly, check if the project SDK is correctly configured or not. Here the project
language level needs to be configured the same as the project SDK selected
during the Project creation. In the case of JDK 11, please follow instructions as
specified in figure no 9:
8
In project Tab: Graphical User Interface
and Java Database
Project SDK 11 Connectivity
Project Language Level: 11- Local Variable Syntax
for lambda Parameters
In Module Tab:
Sources Language Level: 11- Local Variable Syntax
for lambda Parameters
Dependency: Module SDK 11
if you are using JDK-8, you must select Project SDK 8 and Project Language Level:
8 – Lambdas, Type annotations etc. If in your case, you have to set it as per your
JDK version, you are having on your PC/laptop.
Now you will no longer get any errors as you observed in the figure no 7, but still you
will find that if you try to run this application, you will get an Error: “JavaFX
runtime components are missing, and are required to run this application”. This
error is only in case of JDK 11, but JDK 8 you will not have this issue.
9
Introduction to GUI in
Java
Figure 11(a): Default Project without error while useing JDK 11
To fix this error, you need to add a module - info.Java file in the source code
directory, which define the JavaFX control so that the code will work with JDK 11.
Righ click on src folder → New-->Module-Info.Java and add the following line of
codes:
module JavaFXFirstProgramme
{
requires Javafx.fxml;
requires Javafx.controls;
opens sample;
}
No test run the application; you will get the following output:
Finally, we have a directory structure of the First JavaFX Project as shown in figure
no 12.
In this section, we will discuss the features of JavaFX along with its components. As
per the official JavaFX documentation, the following features have been incorporated
10
since the release of JavaFX 8 and later versions. The main items which were Graphical User Interface
and Java Database
announced since the release of JavaFX 8 are given below: Connectivity
● JavaFX is completely written in Java which contains classes and interfaces.
Its API is designed for alternative use of Java Virtual Machines (JVM) such
as JRuby and Scala.
● JavaFX supports two types of coding styles FXML and Scene builder. FXML
is an XML based interface; however, scene builder is a pure Java interface.
Scene builder in JavaFX is used for interactively designing the graphical user
interface (GUI). Scene builder in JavaFX creates FXML, which can be ported
to an IDE where a developer can also add the application's business logic.
● JavaFX supports WebView using WebKitHTML technology to embed web
pages. JavaScript running in WebView can be called by Java APIs. Since the
release of JavaFX 8, it has also supported HTML5 containing Web Sockets,
Web Workers, Web Fonts and printing capabilities features.
● Some JavaFX features can be implemented in existing Swing applications,
such as enabled web content and rich graphics media playback. This feature
has been incorporated since the release of JavaFX 8. All the key controls are
required to develop full-featured application, which is available in JavaFX 8
release, including standard Web Technology such as CSS (e.g., DatePicker
and TreeTableView controls are also available in JavaFX including a public
API for CSS Styleable class which allows objects to be styled by CSS.)
● The 3D Graphics libraries are introduced in JavaFX 8 release. API for
Shape3D (Box, Cylinder, MeshView and Sphere subclasses), SubScene,
PickResult, Material, SceneAntialiasing and LightBase (AmbientLight,
PointLight subclasses) are added in 3D Graphics libraries. It also comprises of
the Camera API class.
● Canvas API: This API allows drawing directly within an area of the JavaFX
scene that contains one graphical element which is also known as node.
● Printing API: The Javafx.print package is included in Java SE 8 release
provides the public classes for the JavaFX Printing API.
● Rich Text Support: The JavaFX 8 brings enriched text support to JavaFX
comprising bi-directional text and complex text scripts such as Thai and
Hindu in controls and multi-line, multi-style text in text nodes.
● Multi-touch Support: The JavaFX provides support for multi-touch operations
based on the capabilities of the underlying platform.
● Hi-DPI support: The JavaFX 8 also supports Hi-DPI displays(Hi-DPI
displays have increased pixel density).
● Hardware-accelerated graphics pipeline: The JavaFX graphics are based on
the graphics rendering pipeline (Prism). JavaFX allows smooth graphics that
render quickly through Prism when it is used with a supported graphics card
or graphics processing unit (GPU). If a system does not feature one of the
recommended GPUs supported by JavaFX, then the Prism defaults that to the
software rendering stack.
● High-performance media engine: The media pipeline supports the playback of
web multimedia content. It provides a stable, low-latency media framework
that is based on the ‘GStreamer’ multimedia framework.
● Self-contained application deployment model: Self-contained application
packages have all of the application resources and a private copy of the Java
and JavaFX runtimes. They are distributed as native installable packages and
11
Introduction to GUI in
Java provide the same installation and launch experience as native applications for
that operating system.
The above items related to JavaFX are given here to make you aware of the
various features and supports provided by JavaFX8. Detailed coverage of the
above items/points are beyond scope of this course.
Your familiarity with the form components available in HTML will help you learn
JavaFX components. In JavaFX many components are available for developing GUI.
In this section, you will learn components in JavaFX . JavaFX controls are the
components that provide control functionalities in application development using
JavaFX. In GUI Programming, the UI element is the core graphical element that users
see and interact with. JavaFX also provides a wide list of common elements/controls
(e.g., label, checkbox , textbox, menu, a button, radio button, table, tree view, date
picker etc.) from basic to advanced level of uses in JavaFX programming. The
package “Javafx.controls” in JavaFX defines various classes to create the GUI
components (controls). The package “Javafx.scene.chart” define various types of
charts and package. The “Javafx.scene.Scene” provides the scene and its
components that are available for the JavaFX UI toolkit. JavaFX supports several
controls like Table view, Treeview, FileChooser, date picker, button text field etc.
Controls are mainly nested inside a layout component, and it manages the layout of
controls. The following list of important controls available in JavaFX:
Every component needs to be initialized with a new key before it is used. Let us see
some important components one by one:
import Javafx.application.Application;
import Javafx.fxml.FXMLLoader;
import Javafx.scene.Parent;
import Javafx.scene.Scene;
import Javafx.scene.control.Accordion;
import Javafx.scene.control.Label;
import Javafx.scene.control.TitledPane;
import Javafx.scene.layout.VBox;
12
import Javafx.stage.Stage; Graphical User Interface
and Java Database
public class MyAccordionControlExample extends Application Connectivity
{
@Override
public void start(Stage primaryStage) throws Exception
{
Parent root = FXMLLoader.load(getClass().getResource("mySample.fxml"));
primaryStage.setTitle("Accordion Control Example");
primaryStage.setScene(new Scene(root, 500, 500));
Output:
13
Introduction to GUI in
Java ColorPicker: It is a component used to choose or manipulate color in a
dialog box. The ColorPicker control is implemented by the class
“Javafx.scene.control.ColorPicker”.
CheckBox: This component enables users to check/tick a component that
can be either on (true) or off (false). The CheckBox control is
implemented by the class “Javafx.scene.control.CheckBox”.
RadioButton: This component is used in a situation where one needs to
have either an ON (true) or OFF (false) state in a group. This control is
implemented by the class “Javafx.scene.control.RadioButton”.
ListView: A ListView component of JavaFX is used to present the user
with a scrolling list of text items. This control is represented by the class
“Javafx.scene.control.ListView”.
TextField: A TextField component in JavaFX allows users to edit a
single line text. It is implemented by the call
“Javafx.scene.control.TextField”.
PasswordField: A PasswordField is a special text component that allows
the user to enter a secure or sensitive text in a text field. It differs from
TextField because the entered text does not show after typing. It is
implemented by the class “Javafx.scene.control.PasswordField”.
Scrollbar: A Scrollbar component is used to allow the user to select from
a range of values.
FileChooser: A FileChooser control providess a dialog window from
which the user can select a file.
ProgressBar: Using this component, as the task progresses towards
completion, the task's percentage of completion can be shown.
Slider: A Slider lets the user graphically select a value by sliding a knob
within a bounded interval.
⮚ HBox: The HBox layout organizes all the nodes in an application in a single
horizontal row. The class named HBox of the package Javafx.scene.layout
signifies the text horizontal box layout.
Syntax in FXML:
<?import Javafx.scene.layout.HBox?>
15
Introduction to GUI in
Java <HBox fx:controller="ignou.Controller" xmlns:fx=http://Javafx.com/fxml
alignment="center">
<Label text="Welcome to HBox Layout using FXML"/>
<Button text="Button 1"/>
<Button text="Button 2"/>
</HBox>
Syntax in Java:
Label label1 =new Label("Welcome to HBox Layout with Pure Java code");
Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button Number 2");
HBox hbox = new HBox(label1, button1, button2);
primaryStage.setScene(new Scene(hbox, 500, 275));
⮚ VBox: The VBox layout organizes all the nodes in our application in a single
vertical column. The class named VBox of the package Javafx.scene.layout
denotes the text Vertical box layout.
Syntax in FXML:
<?import Javafx.scene.layout.VBox?>
<VBox fx:controller="ignou.Controller" xmlns:fx="http://Javafx.com/fxml"
alignment="center">
<padding>
<Insets bottom="10" right="10"/>
</padding>
<Label text="Welcome to VBox Layout"/>
<Button text="Button 1"/>
<Button text="Button 2"/>
</VBox>
Syntax in Java:
Label label1 = new Label("Welcome to VBox Layout using Java Code");
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
VBox vbox = new VBox(label1, button1, button2);
primaryStage.setScene(new Scene(vbox, 500, 275));
⮚ BorderPane: The Border Pane layout organizes the nodes in our applications
in top, left, right, bottom and center positions. The class BorderPane of the
package Javafx.scene.layout is used for the border pane layout.
Syntax in FXML:
<?import Javafx.scene.layout.BorderPane?>
<BorderPane fx:controller="ignou.Controller"
xmlns:fx="http://Javafx.com/fxml">
<bottom>
<HBox xmlns:fx="http://Javafx.com/fxml">
<padding>
<Insets bottom="10" right="10"/>
</padding>
<Label text="Welcome to BorderPane Layout"/>
<Button text="Button 1" prefWidth="90"/>
<Button text="Button 2" prefWidth="90"/>
</HBox>
16
</bottom> Graphical User Interface
and Java Database
</BorderPane> Connectivity
Syntax in Java:
Label label1 = new Label("Welcome to BorderPane Layout using Java
Code");
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
BorderPane borderPane = new BorderPane();
borderPane.setTop(label1);
borderPane.setRight(button1);
borderPane.setLeft(button2);
primaryStage.setScene(new Scene(borderPane, 500, 275));
Syntax in Java:
Label label1 = new Label("Welcome to StackPane Layout using Java Code");
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
StackPane stackPane = new StackPane();
stackPane.setMargin(label1, new Insets(50, 50, 50, 50));
ObservableList observableList = stackPane.getChildren();
observableList.addAll(label1, button1, button2);
primaryStage.setScene(new Scene(stackPane, 700, 275));
⮚ TextFlow: The Text Flow layout organizes multiple text nodes in a single
flow. The class TextFlow in the package Javafx.scene.layout denotes the text
flow layout.
Syntax in FXML:
<?import Javafx.scene.text.TextFlow?>
<TextFlow fx:controller="ignou.Controller"
xmlns:fx="http://Javafx.com/fxml" >
<padding>
<Insets bottom="10" right="10"/>
17
Introduction to GUI in
Java </padding>
<Label text="Welcome to TextFlow Layout"/>
<Button text="Button 1"/>
<Button text="Button 2"/>
</TextFlow>
Syntax in Java:
Text text1 = new Text("Welcome to TextFlow Layout");
text1.setFont(new Font(15));
text1.setFill(Color.DARKSLATEBLUE);
textFlowPane.setTextAlignment(TextAlignment.JUSTIFY);
textFlowPane.setPrefSize(10, 10);
textFlowPane.setLineSpacing(5.0);
ObservableList list1 = textFlowPane.getChildren();
list1.addAll(text1, btn1);
Scene scene = new Scene(textFlowPane);
stage.setTitle("text Flow Pane Example");
stage.setScene(scene);
stage.show();
Syntax in Java:
Text text1 = new Text("Welcome to AnchorPane Layout");
text1.setFont(new Font(15));
text1.setFill(Color.DARKSLATEBLUE);
Button btn1 = new Button("Button 1");
Btn1.setFont(Font.font("Times new Roman", FontWeight.BOLD, 12));
18
Graphical User Interface
and Java Database
⮚ Connectivity
TilePane: Using Tile Pane layout the nodes in an application are added in the
form of uniformly sized tiles. The class TilePane is in the package
Javafx.scene.layout denotes the TilePane layout.
Syntax in FXML:
<?import Javafx.scene.layout.TilePane?>
<TilePane fx:controller="ignou.Controller"
xmlns:fx="http://Javafx.com/fxml">
<padding>
<Insets bottom="10" right="10"/>
</padding>
<Label text="Welcome to TilePane Layout"/>
<Button text="Button 1" />
<Button text="Button 2"/>
</TilePane>
Syntax in Java:
Text text1 = new Text("Welcome to TilePane Layout");
text1.setFont(new Font(15));
text1.setFill(Color.DARKSLATEBLUE);
Button btn1 = new Button("Button 1");
Btn1.setFont(Font.font("Times new Roman", FontWeight.BOLD, 12));
TilePane tilePane1 = new TilePane();
tilePane1.getChildren().add(text1);
tilePane1.getChildren().add(btn1);
Scene scene = new Scene(tilePane1, 10, 10);
⮚ GridPane: The Grid Pane layout is used to organize the nodes in an
application as a grid of rows and columns. This layout comes handy while
creating forms using JavaFX. The class GridPane in the package
Javafx.scene.layout denotes the GridPane layout.
Syntax in FXML:
<?import Javafx.scene.layout.GridPane?>
<GridPane fx:controller="ignou.Controller"
xmlns:fx="http://Javafx.com/fxml" alignment="center" hgap="10"
vgap="10">
<Label text="Welcome to Gridpane Layout" GridPane.rowIndex="0"
GridPane.columnIndex="1"/>
<Button text="Button 1" GridPane.columnIndex="0"
GridPane.rowIndex="1"/>
<Button text="Button 2" GridPane.columnIndex="0"
GridPane.rowIndex="2"/>
</GridPane>
Syntax in Java:
Text text1 = new Text("Welcome to Gridpane Layout");
text1.setFont(new Font(15));
text1.setFill(Color.DARKSLATEBLUE);
Button btn1 = new Button("Button 1");
Btn1.setFont(Font.font("Times new Roman", FontWeight.BOLD, 12));
19
Introduction to GUI in
Java
GridPane gridPane1= new GridPane ();
gridPane1.add(text1, 0, 0, 1, 1);
gridPane1.add(btn1, 1, 0, 1, 1);
Scene scene = new Scene(gridPane1, 40, 20);
⮚ FlowPane: The flow pane layout wraps all the nodes in a flow. A horizontal
flow pane wraps the elements of the pane at its height, while a vertical flow
pane wraps the elements at its width. The class FlowPane in the package
Javafx.scene.layout denotes the Flow Pane layout.
Syntax in FXML:
<?import Javafx.scene.layout.FlowPane?>
<FlowPane fx:controller="ignou.Controller"
xmlns:fx="http://Javafx.com/fxml" orientation="HORIZONTAL">
<padding>
<Insets bottom="10" right="10"/>
</padding>
<Label text="Welcome to FlowPane Layout"/>
<Button text="Button 1" />
<Button text="Button 2"/>
</FlowPane>
Syntax in Java:
Text text1 = new Text("Welcome to FlowPane Layout");
text1.setFont(new Font(15));
text1.setFill(Color.DARKSLATEBLUE);
Button btn1 = new Button("Button 1");
Btn1.setFont(Font.font("Times new Roman", FontWeight.BOLD, 12));
flowpane1.getChildren().add(text1);
flowpane1.getChildren().add(btn1);
Create node: First of all, create the required nodes of the JavaFX application
by instantiating their respective classes.
Instantiate the respective class of the required layout: After creating the
nodes (and completing all the operations on them), instantiate the class of the
required layout.
Set the properties of the layout: After instantiating the class, you need to set
the layout's properties using their respective setter methods.
Add all the created nodes to the layout: Finally, you need to add the object
of the shape to the group by passing it as a parameter of the constructor.
20
package org.ignou.gui; Graphical User Interface
import Javafx.application.Application; and Java Database
Connectivity
import Javafx.geometry.Insets;
import Javafx.geometry.Pos;
import Javafx.scene.Scene;
import Javafx.scene.control.Button;
import Javafx.scene.control.Label;
import Javafx.scene.control.PasswordField;
import Javafx.scene.control.TextField;
import Javafx.scene.layout.GridPane;
import Javafx.scene.layout.HBox;
import Javafx.scene.text.Font;
import Javafx.scene.text.FontWeight;
import Javafx.scene.text.Text;
import Javafx.stage.Stage;
public class MyGridPaneExample extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
primaryStage.setTitle("Welcome to GridPane Layout in JavaFx
using Pure Java code");
21
Introduction to GUI in
Figure 14: Output Screen of Example no 4
Java
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
To implement CSS Style in JavaFX through style file following steps need to be
followed:
● Create a resources/css folder in the project folder
● Add CSS file(Style Sheet) in css folder
● Write rules in Stylesheet as explained above
● Set scene property using getStylesheets() method
getStylesheets().add("file:resources/css/style.css");
● Set style/CSS ID in JavaFX’s component using getStyleClass() method
getStyleClass().add("button1”); (where button1 is the
same ID ruled in CSS.)
import Javafx.application.Application;
import Javafx.scene.Scene;
import Javafx.scene.control.Button;
import Javafx.scene.layout.HBox;
import Javafx.scene.text.Text;
import Javafx.stage.Stage;
@Override
public void start(Stage stage)
{
Text text1 = new Text();
text1.setText("Welcome to use of CSS in JavaFX");
23
Introduction to GUI in
Java Button yesBtn = new Button("Yes");
scene1.getStylesheets().add("file:resources/css/style.css");
stage.setScene(scene1);
stage.setTitle("HTML CSS Styling Example");
stage.show();
}
}
2. Create style sheet file in the location:
resources/css/style.css
.button
{
-fx-background-color: blue;
-fx-text-fill: white;
-fx-font-size: 10px;
-fx-font: Arial;
-fx-alignment: left;
}
.button1
{
-fx-background-color: red;
-fx-text-fill: white;
-fx-font-size: 15px;
-fx-font: Times new roman;
-fx-alignment: center;
}
.button2
{
-fx-background-color: green;
-fx-text-fill: white;
-fx-font-size: 20px;
-fx-font: Arial;
-fx-alignment: right;
}
.text1
{
-fx-font: Arial;
-fx-font-size: 20px;
}
Output:
24
Graphical User Interface
and Java Database
Connectivity
As explained above, a single element in the scene is called a node which handles
many types of content, which also include text. Text elements can be added as a
textbox, label and using other components. The package of Text node is
“Javafx.scene.text” and represented by the class named Text which is inherited from
the Node class in JavaFX that used to display text. As per requirement, it can apply
effects, transformations and animation to text nodes. All node types permit us to
provide cultured text contents that fulfil the demands of modern rich Internet
applications using all such features.
To add a text object to an application, first, instantiate a class as follow:
Text text1=new Text ();
The data type of a class Text is string type which means it will store String text; to do
that, we have to set the value using setText() method after instantiating a Text node:
String textString= "Welcome to Text Node";
text1.setText(textString);
Setting Text Position
A position of the text can be defined or set by specifying the value of the properties x
and y using their respective setter methods namely setX() and setY():
text1.setX(50);
text1.setY(50);
Setting Text Font and Color
Text Font and color can be defined or set using its properties. You can use an instance
of the “Javafx.scene.text.Font” class. The Font.font() method allows to specify the
font family name and size. setFill() method can be used for setting a text color. Syntax
of setting Text font and color as follow:
text1.setText("Setting Text Font and color");
text1.setFont(Font.font ("Times New Roman", 20));
text1.setFill(Color.RED);
Alternatively, we can also use a system font, which is platform dependent, means text
font varies as per platform in which the application is running. To use this
functionality, you have to call the Font.getDefault() method.
text1.setFont(Font.getDefault ());
Alternatively, we can also use custom fonts in JavaFX. For using a custom font, you
can embrace a TrueType font (.ttf) or an OpenType (.otf) in the application. To
comprise font as a custom font, follow the following procedure:
● Create a resources/fonts folder in the project folder.
● Copy your font files to the fonts subfolder in the project created.
● In the source code, load the custom font as follow
text1.setFont(Font.loadFont("file:resources/fonts/AlexBrush-Regular.ttf", 120));
25
Introduction to GUI in
Java Setting Text Bold or Italic
Use the FontWeight constant of the setFont() method to make Bold Text using follow
syntax:
text1.setFont(Font.font ("Times New Roman", FontWeight.BOLD, 20));
Use the FontPosture constant of the setFont() method to make italic Text using follow
syntax:
text1.setFont(Font.font ("Times New Roman", FontPosture.ITALIC, 20));
package org.ignou.gui;
import Javafx.application.Application;
import Javafx.geometry.Pos;
import Javafx.scene.Group;
import Javafx.scene.Scene;
import Javafx.scene.layout.GridPane;
import Javafx.scene.paint.Color;
import Javafx.scene.text.Font;
import Javafx.scene.text.FontPosture;
import Javafx.scene.text.FontWeight;
import Javafx.scene.text.Text;
import Javafx.stage.Stage;
Output:
27
Introduction to GUI in
Java
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
1.8 SUMMARY
This unit gives an overview of the graphical user interface(GUI) in Java. In this unit
AWT/Swing/JavaFX and User Interface Components of JavaFX are explained. Also
GUI programming examples are given using coding style in AWT, Swing and
JavaFX. Also, it is explained how to setup a project for JavaFX using intellij Idea and
create the First Hello World program. The unit described how to work with layout in
JavaFX along with coding style using FXML and pure Java code. This unit also
explained concept of HTML Contents uses in JavaFX, text and various text effects in
JavaFX with the help of programming examples.
28
Graphical User Interface
It has lightweight GUI components. It has heavyweight GUI components. and Java Database
It supports pluggable look and feel. It doesn't support pluggable look and Connectivity
feel.
It provides more advanced it provides less components than Swing
components then AWT like tables,
lists, scrollpanes, colorchooser,
tabbedpane etc.
It supports MVC design pattern It does not follow the MVC design
pattern.
Execution is faster Execution is slower
The components of swing do not The components of AWT require more
require much memory space memory space
Carl Dea, Gerrit Grunwald, José Pereda, Sean Phillips and Mark Heckler
“JavaFX 9 by Example”, Apress,2017.
● Sharan, Kishori, “ Beginning Java 8 APIs, Extensions and Libraries: Swing,
JavaFX, JavaScript, JDBC and Network Programming APIs”, Apress, 2014.
● Package and classes in AWT
(https://docs.oracle.com/Javase/7/docs/api/Java/awt/package-summary.html)
● JavaFXGetting Started with JavaFX
Release 8(https://docs.oracle.com/Javase/8/Javafx/get-started-
tutorial/index.html)
● https://www.oracle.com/Java/technologies/Javase/Javafx-docs.html
● https://docs.oracle.com/Javase/7/docs/api/Java/awt/package-summary.html
● https://openjfx.io/openjfx-docs/
● https://docs.oracle.com/Javase/8/Javafx/get-started-tutorial/jfx-
overview.htm#BABEDDGH
● https://gluonhq.com/products/Javafx/
● https://openjfx.io/Javadoc/15/Javafx.controls/Javafx/scene/control/package-
summary.html
30