0% found this document useful (0 votes)
14 views

Chapter 1 JAVAfx

JavaFX is a Java library that enables developers to create rich graphical user interfaces with advanced features such as animations, visual effects, and 3D graphics. It includes built-in UI controls, supports FXML for UI design, and allows integration with Swing applications. JavaFX applications are structured around stages, scenes, and nodes, and can be launched using the standard Java main method.

Uploaded by

tsionyosef46
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)
14 views

Chapter 1 JAVAfx

JavaFX is a Java library that enables developers to create rich graphical user interfaces with advanced features such as animations, visual effects, and 3D graphics. It includes built-in UI controls, supports FXML for UI design, and allows integration with Swing applications. JavaFX applications are structured around stages, scenes, and nodes, and can be launched using the standard Java main method.

Uploaded by

tsionyosef46
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
You are on page 1/ 64

JAVAFX

JavaFX: Introduction
 JavaFX is a collection of Java packages that lets
you add fancy graphical user interfaces to your
Java applications.
 JavaFX provides a rich set of graphics and media
API’s and it leverages the modern Graphical
Processing Unit through hardware accelerated
graphics.
 JavaFX also provides interfaces using which
developers can combine graphics animation and UI
control.
 It allows you create traditional windows-style user
interfaces that include familiar controls such as:
 labels,
 buttons,
 textboxes,
 check boxes,
 drop-down lists, and so on.

 But you can also adorn these user interfaces with


fancy effects such as light sources, perspective, and
animation. Hence the FX in JavaFX
 Prior to JavaFX, the main way to create graphical
user interfaces in Java was through the Swing API.
 JavaFX is similar to Swing in many ways

 It has been around as an add-on package for a


while, but beginning with Java version 8 (JDK 8), it
is now an official standard part of the Java
platform
 i.e,you can run your JavaFX programs on any device
that includes version 8 of JRE
 Although Swing is still supported in Java 8 Oracle is
concentrating new features on JavaFX.
 Eventually, Swing will become obsolete

 Compared to Swing, JavaFX uses more advanced


features
 More than just creating simple GUIs, you can really
improve the appearance of your interface by using
cascading Style Sheets (CSS)
 Besides CSS, JavaFX offers even many other capabilities. The
followings are some of them:
 Visual effects:
 You can add a wide variety of visual effects to your user interface
elements, including shadows, reflections, blurs, lighting, and
perspective effects.
 Animation:
 You can specify animation effects that apply transitions gradually
over time.
 Charts:
 You can create bar charts, pie charts, and many other chart types
using the many classes of the javafx.scene.chart package.
 3-D objects:
 You can draw three-dimensional objects such as cubes, cylinders,
spheres, and more complex shapes
 Touch interface:
 JavaFX can handle touchscreen devices, such as
smartphones and tablet computers with ease.
 Property bindings:
 JavaFX lets you create properties, which are special data
types that can be bound to user interface controls
 For example, you can create a property that represents
the price of an item being purchased and then bind a
label to it.
 Then, whenever the value of the price changes, the value
displayed by the label is updated automatically.
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.
 JavaFX applications are platform independent.

 FXML
 JavaFX features a language known as FXML, which is a HTML like
declarative markup language.
 The main 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

 Swing Interoperability
 In a JavaFX application, you can embed Swing content using
the Swing Node class.
 Similarly, you can update the existing Swing applications with
JavaFX features like embedded web content and rich graphics
media.
 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 which will help you improve the design
of your application
 Canvas and Printing API
 JavaFX provides Canvas, an immediate mode style of rendering API.
 Within the package javafx.scene.canvas 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 javafx.print.
 Integrated Graphics library
 JavaFX provides classes for 2d and 3d graphics
Architecture
 There are set of classes and interfaces which are used to build GUI
applications using JavaFX API
 javafx.animation
 Contains classes to add transition based animations such as fill,
fade, rotate, scale and translation, to the JavaFX nodes.

 javafx.application
 Contains a set of classes responsible for the JavaFX application
life cycle.

 javafx.css
 Contains classes to add CSS–like styling to JavaFX GUI
applications.
 javafx.event
 Contains classes and interfaces to deliver and handle JavaFX
events.
 javafx.geometry
 Contains classes to define 2D objects and perform operations on
them.
 javafx.stage
 the top level container classes for JavaFX application.

 javafx.scene
 provides classes and interfaces to support the scene graph.

 it also provides sub-packages such as canvas, chart, control,


effect, image, input, layout, media, paint, shape, text, transform,
web, etc.
Architecture…..cont’d
 Scene Graph
 In JavaFX, the GUI Applications were coded using a Scene
Graph.
 It is the starting point of the construction of the GUI
Application.
 It holds the (GUI) application primitives that are termed as
nodes and which may includes:
 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.
 All of these nodes are arranged in a hierarchical
order
 A node instance can be added to a scene graph
only once.

 These nodes can have Effects, Opacity, Transforms,


Event Handlers, Application Specific States.
 Prism
 is a high performance hardware–accelerated graphical pipeline
that is used to render the graphics in JavaFX.
 It can render both 2-D and 3-D graphics.

 When used with a supported Graphic Card or GPU, it offers


smoother graphics.

 GWT (Glass Windowing Toolkit)


 provides services to manage Windows, Timers, Surfaces and
Event Queues.
 GWT connects the JavaFX Platform to the Native Operating
System.
 WebView
 Using JavaFX, you can also embed HTML content in to a scene
graph.
 It 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.

 Allows you control web content from java


 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
 Mp3, WAV, AIFF, FLV

 Classes and interfaces used to provide media functionality are included


in javafx.scene.media
Program Structure
 Three major components are involved in JavaFX application.
 Stage
 Scene
 Nodes

 Stage:
 Is also referred to as window
 All JavaFX application should be contained in Stage
 It is JavaFX applications’ highest-level window
 Is represented by Stage class in javafx.stage package
 A primary stage will be created by the platform you are using
 As in Swing, you have to call the show() method to display the
contents of a stage
 Scene:
 It is physical content of JavaFX application
 Contains all the contents of a scene graph
 All UI elements will be included in Scene
 Is represented by the Scene class of javafx.scene package.
 At a single instance, the scene object is added to only one stage.

 Nodes:
 Is a visual object of a scene graph
 Scene Graph: is hierarchical data structure representing the contents of
a scene
 May include Geometrical objects, UI controls, Containers, Media
elements
 Is represented by Node class of javafx.scene package
 A Node could be
 Root,
 The first Scene Graph is the Root Node
 Branch/ Parent
 Nodes, that are not root, but have child nodes are Parent Nodes
 Could be
 Group: is a collective node that contains a list of children nodes
 Any effect applied to the group will also be applied to all the child
nodes
 Region: base class of Node based UI Controls, such as Pane, and
Control
 WebView: manages the web engine and displays is content
 Leaf
 Node with no child
 Example: ImageView, Box, Rectangle
Getting Started…
 To create JavaFx programs, you need to import some packages. The
followings are common:
 javafx.application: defines the core class on which all JavaFX
applications depend: i.e. The Application Class
 javafx.stage: defines Stage class.

 javafx.scene: defines the Scene class.

 javafx.scene.layout: defines a special type of user interface


element called a layout manager.
 The job of a layout manager is to determine the position of each
control displayed in the user interface.
 javafx.scene.control: contains the classes that define individual user
interface controls such as buttons, text boxes, and labels.
 The Application class
 To create a JavaFX application, you need to instantiate the
Application class and implement its abstract method start().

 This method is where you are going to write the code for your
JavaFX Application.

 Application class is your entry point to the application in JavaFX.

 It is responsible for managing what is called the life cycle of a


JavaFX application
 The lifecycle consists of the following steps:
 Create an instance of the Application class.
 Call the init() method.
 The default implementation of the init method does nothing, but
you can override the init method to provide any processing you
want to be performed before the application’s user interface
displays.
 Call the start() method.
 The start method is an abstract method, you must provide your
own version of it.
 It is responsible for building and displaying the user interface.
 Wait for the application to end,
 This commonly happens when the user signals the end of the
program by closing the main application window or choosing the
program’s exit command.
 During this time, the application isn’t really idle

 Call the stop() method


 Like the init() method, the default implementation of the stop
method doesn’t do anything,
 You can override it to perform any processing necessary as the
program terminates, such as closing database resources or saving
files.
 In order to create a typical JavaFX application, your start() method
has to include the following activities.
 Preparing the Scene Graph

 Preparing a Scene

 Preparing a stage

 Preparing the Scene Graph


 You have to prepare a scene graph with required nodes

 As a root node, you can choose from the Group, Region or


WebView.
 Group: is represented as a Group class of the javaxfx.scene
Group groupName = new Group();
 You can get the children of the Group by calling the getChildren() method.

 This method returns an object of ObservableList class, which holds the


nodes.
 You can call add(NodeObject) of this class to add a object of a node.
ObservableList ol = groupname.getChildren();
ol.add(someNodeObject);

 Alternatively, you can pass the node object to a Group class upon instance.
 Region: is the Base class of all the JavaFX Node-based UI Controls,
such as
 Chart

 is the base class of all the charts and it belongs to the


package javafx.scene.chart
 has two sub classes, − PieChart and XYChart.
 These two in turn have subclasses such as AreaChart, BarChart,
BubbleChart, etc. used to draw different types of XY-Plane
Charts in JavaFX.
 Pane

 is the base class of all the layout panes such as AnchorPane,


BorderPane, DialogPane, etc. This class belong to a package
that is called as − javafx.scene.layout.
 Control
 is the base class of the User Interface controls such as Accordion,
ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This
class belongs to the package javafx.scene.control.

 You can use these classes to insert various UI elements in your


application.

 In a Group, you can instantiate any of the above-mentioned


classes and use them as root nodes
Example BorderPane pane = new BorderPane();
ObservableList list = pane.getChildren();
list.add(NodeObject)
 Preparing the Scene
 You can create a Scene by instantiating Scene class of javafx.scene

 While instantiating, it is mandatory to pass the root object to the


constructor of the scene class.
Example: Scene scene = new Scene(pane);
 You can also pass other two parameters representing the height
and width of the scene.
Example: Scene scene = new Scene(pane, 500, 250);
 Preparing the Stage
 It is represented by the Stage class of the javafx.stage
package.
 An object of this class is passed as a parameter of
the start() method of the Application class.
 This object is used to perform various operations on the stage.
 The common ones are:
 Set the title for the stage using the method setTitle().
 Attach the scene object to the stage using the setScene() method.
 Display the contents of the scene using the show() method

 Example:
public void start(Stage primaryStage)
{
primaryStage.setScene(scene);
primaryStage.setTitle(“My First JavaFx App");
primaryStage.show();
}
Launching the application
 Recall, main() method is standard entry point for Java programs

 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
 Example
public static void main(String args[])
{
launch(args);
}
Terminating the JavaFX Application
 When the last window of the application is closed, the JavaFX
application is terminated implicitly.

 If you need, you can turn this behavior off by passing the Boolean
value “False” to the static method setImplicitExit()

 Then, you can terminate a JavaFX application explicitly using the


methods Platform.exit() or System.exit(int).
Basic UI controls
 Every user interface will at least have the following
main aspects:
 UI Elements:
 These are the core visual elements which the user eventually
sees and interacts with.
 Layouts:
 definehow UI elements should be organized on the screen
and provide a final look and feel to the GUI
 Behavior:
 Theseare events which occur when the user interacts with UI
elements.
UI Elements
 The javafx.scene.control package contains several
classes used to create various GUI components/
controls

 Remember that each control is represented by a


class
 Instantiatingtheir respective class will allow you to
create these controls
Control Name Description
Label Component for placing texts
Button Creates a labelled button
RadioButton Control which could be either in On or Off state
CheckBox Control which could be either in On or Off state, and allowing multiple selection
ListView Presents the user with a scrolling list of items
TextField Allows for the editing of a single line of text
PasswordField Text entry component specialized for password
Scrollbar Represents a scroll bar in order to enable a user to select from range of values

FileChooser A dialog window from which the user can select a file
ProgressBar Displays tasks completion percentage
Slider lets the user graphically select a value by sliding a knob within a bounded
interval
ColorPicker Provides a pane of controls designed to allow a user to manipulate and select a
color
Menu Implements menus
Label
 Represented by javafx.scene.control.Label class
 Label is the component that is used to place any text information on
the screen.
 It is mainly used to describe the purpose of the other components to
the user.

 Note: You can not set a focus on the label using the Tab key.
 Constructors:
Label()
Label(String text)
Label(String text, Node graphics)
 Example :

public void start(Stage primaryStage) throws Exception {


StackPane root = new StackPane();
FileInputStream input= new FileInputStream(“imageURL");
Image image = new Image(input);
ImageView imageview=new ImageView(image);
Label my_label=new Label("Home",imageview);
Scene scene=new Scene(root,300,300);
root.getChildren().add(my_label);
primaryStage.setScene(scene);
primaryStage.setTitle("Label Class Example");
primaryStage.show();
}
Button
 Represented by javafx.scene.control.Button class.
 An event is generated whenever the button gets clicked

 Example; Button btn = new Button(“Click Me");


 You can also use the settext(String s) method of the button to set the
label
 Example: btn.setText(“Click Me”);
 You can also wrap the text of the button into multiple lines if the text
to be displayed is too long.
 This can be done by calling a setter
method setWrapText(boolean) on the instance of Button class.

 Pass the boolean value true in the method wherever required.


 Button class also contains a constructor which can accept graphics along
with the text displayed on the button.
 Example: Button b= new Button(“Click Me”, GraphicsObj);

 Or you can use setGraphic(GraphicsObj);

 Example:
FileInputStream input=new FileInputStream(“imageURL");
Image image = new Image(input);
ImageView img=new ImageView(image);

Button btn=new Button();


btn.setGraphic(img);
 You can set action to a Button using the setOnAction() method.
 An object of the anonymous class implementing
the handle() method, is passed in this method as a parameter.
 Example:
Button btn=new Button(“Click Me”);
btn.setOnAction(new EventHandler<ActionEvent>() {
publicvoid handle(ActionEvent e) {
System.out.println("Button clicked"); }
 Or you can also use lambda expressions to handle the events
 Example:
btn.setOnAction(e->System.out.println(""));
RadioButton
 It forces the user to select a single option among all.
 A ToggleGroup has to be used to group alike radios
 Example:
ToggleGroup group = new ToggleGroup();
RadioButton rad1 = new RadioButton("option 1");
RadioButton rad2 = new RadioButton("option 2");

rad1.setToggleGroup(group);
rad2.setToggleGroup(group);
CheckBox
 The Check Box is used to provide more than one choices to the
user.
 Example:
CheckBox c1 = new CheckBox(“Java");
CheckBox c2 = new CheckBox(“Python");
HyperLink
 You can use hyper-links to refer the web pages.
 It is similar to anchor links in HTML
 Constructors
 HyperLink hyp1= new HyperLink()
 HyperLink hyp1= new HyperLink(String text)
 HyperLink hyp1= new HyperLink(String text, Node graphic)
 Example

FileInputStream input=new FileInputStream(“imageURL");


Image image = new Image(input);
ImageView img=new ImageView(image);
HyperLink hyp = new HyperLink(img);
Slider
 JavaFX slider is used to provide a pane of option 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.
 The constructor accepts three arguments: the minimum value,
the maximum value, and the initial value of the slider.
 Example:
 Slider slider = new Slider(1,50,25);

 You can use getValue() method of the slider to get the actual
value of the Slider
ProgressBar
 It is used to show the work progress to the user.

 Example: ProgressBar prog = new ProgressBar(1f);


layout.getChildren().addAll(prog);
 Call the getProgress() method to get the current progress
ProgressIndicator
 Instead of showing the analogue progress to the user, it shows
the digital progress so that the user may know the amount of
work done in percentage.
 Example:
 ProgressIndicator PI=new ProgressIndicator();

 Use the setProgress(double) and getProgress() method to set


and get the progress indicator value.
ScrollBar
 Allows the user to scroll down the application pages.
 Use setOrientation(Orientation) method to set the Vertical or
Horizontal scrollbar.
 The default implementation of ScrollBar needs no argument.
 You can use setMin(), setMax(), and setValue() method to set the
minimum, maximum, and current value of the scrollbar respectively.
 Example:
ScrollBar s = new ScrollBar();
s.setMin(0);
s.setMax(200);
s.setValue(110);
s.setOrientation(Orientation.VERTICAL);
FileChooser
 enables users to browse the files from th
 provides two types of methods,
 showOpenDialog()
 showSaveDialog()
 Example:
FileChooser file = new FileChooser();
file.setTitle("Open File");
file.showOpenDialog(primaryStage);
NB: Here primaryStage is the Owner Window
Menu
 Menu class provides all the methods to deal with menus.
 First you have to create a MenuBar, which is the container of
all Menus.
 Then you have to create Menus, which will optionally hold
MenuItems.

 The getItems() method of Menus and getMenus() method of


MenuBars will get list of MenuItems and Menus respectively.

 You can call add(Object) method to add additional Menus and


MenuItems.
 Example:
ManuBar menubar = new MenuBar();
Menu Menu1 = new Menu("Menu1");
MenuItem MenuItem1 = new MenuItem("Menu Item 1");
Menu1.getItems().add(MenuItem1);
menubar.getMenus().add(MenuName);
Layouts
 Defines UI styles for scene graph objects.
 It is also considered as the parent node to all other nodes
 Defines the way in which the components are to be seen on the
stage.
 It basically organizes the scene-graph nodes.

 JavaFX provides default layout panes.


 These layout panes are represented by a separate class that
are subclasses of javafx.scene.layout.Pane class.
Layout Classes
Layout Classes Description

BorderPane Organizes nodes in Top, Left, Right, Centre and the Bottom of the screen.

FlowPane Organizes the nodes in the horizontal rows according to the available
horizontal spaces.
Wraps the nodes to the next line if the horizontal space is less than the
total width of the nodes

GridPane Organizes the nodes in the form of rows and columns.

HBox Organizes the nodes in a single row.

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

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

VBox Organizes nodes in a vertical column.


BorderPane
 Constructors:
 BorderPane()
 BorderPane(Node Center)
 BorderPane(Node Center, Node top, Node right, Node bottom,
Node left)

 Example:
 BorderPane bp= new Borderpane();
 Bp.setBottom(new Label(“label at Bottom”));
HBox
 Constructors:
 HBox() : create HBox layout with 0 spacing

 Hbox(Double spacing) : create HBox layout with a spacing


value
 Use setAlignment(Double d) method to set alignment to the
nodes

 Spacing can also be set using setSpacing(Double dd) method

 Use setPadding(Insets ins) to set padding of the nodes


VBox
 Constructors
 VBox() : creates layout with 0 spacing

 VBox(Double spacing) : creates layout with a spacing value of


double type

 VBox(Double spacing, Node children) : creates a layout with the


specified spacing among the specified child nodes

 VBox(Node children) : creates a layout with the specified nodes


having 0 spacing among them
StackPane
 Puts one node on top of the other
 Constructors
 StackPane()

 StackPane(Node Children)

 setAlignment(Pos value) method will be used to set alignment


of children with respect to the panes size
GridPane
 It allows us to add the multiple nodes in multiple rows and
columns.
 It is seen as a flexible grid of rows and columns where nodes
can be placed in any cell of the grid.
Property Description Setter Methods
alignment Represents the alignment of the grid within setAlignment(Pos value)
the GridPane.
gridLinesVisible Lines can be displayed to show the gidpane's setGridLinesVisible(Boolean
rows and columns by setting this property to value)
true.
hgap Horizontal gaps among the columns setHgap(Double value)

vgap Vertical gaps among the rows setVgap(Double value)


 Constructor:
 GridPane(): creates a gridpane with 0 hgap/vgap.

 addRow(rowindex, children) method can be used to add nodes


to specific row indexex.
FlowPane
 Organizes the nodes in a flow that are wrapped at the
flowpane's boundary.

 The horizontal flowpane arranges the nodes in a row and


wrap them according to the flowpane's width.

 The vertical flowpane arranges the nodes in a column and


wrap them according to the flowpane's height.
Property Description Setter Methods

alignment The overall alignment of the setAlignment(Pos value)


flowpane's content.

columnHalignment The horizontal alignment of nodes setColumnHalignment(HPos


within the columns. Value)

hgap Horizontal gap between the columns. setHgap(Double value)

orientation Orientation of the flowpane setOrientation(Orientation


value)

prefWrapLength The preferred height or width where setPrefWrapLength(double


content should wrap in the horizontal value)
or vertical flowpane.

rowValignment The vertical alignment of the nodes setRowValignment(VPos


within the rows. value)

vgap The vertical gap among the rows setVgap(Double value)


 Constructors:
 FlowPane()
 FlowPane(Double Hgap, Double Vgap)
 FlowPane(Double Hgap, Double Vgap, Node children)
 FlowPane(Node... Children)
 FlowPane(Orientation orientation)
 FlowPane(Orientation orientation, double Hgap, Double Vgap)
 FlowPane(Orientation orientation, double Hgap, Double Vgap, Node
children )
 FlowPane(Orientation orientation, Node... Children)
Cascading Style Sheet

You might also like