0% found this document useful (0 votes)
0 views126 pages

Unit 5 Java FX.pptx

This document provides an overview of JavaFX, a Java library for developing desktop and rich internet applications, detailing its event handling, controls, components, and layout management. It covers the structure of JavaFX applications, including the use of stages and scenes, as well as various controls like buttons, checkboxes, and text inputs. Additionally, it explains event handling mechanisms, including key and mouse events, and the layout options available in JavaFX such as FlowPane, HBox, VBox, and BorderPane.

Uploaded by

24z268
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)
0 views126 pages

Unit 5 Java FX.pptx

This document provides an overview of JavaFX, a Java library for developing desktop and rich internet applications, detailing its event handling, controls, components, and layout management. It covers the structure of JavaFX applications, including the use of stages and scenes, as well as various controls like buttons, checkboxes, and text inputs. Additionally, it explains event handling mechanisms, including key and mouse events, and the layout options available in JavaFX such as FlowPane, HBox, VBox, and BorderPane.

Uploaded by

24z268
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

JAVAFX EVENT HANDLING,

CONTROLS AND COMPONENTS


Unit 5
JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS
JAVAFX Events and Controls:
Event Basics – Handling Key and Mouse Events.
Controls: Checkbox, ToggleButton – RadioButtons – ListView
– ComboBox – ChoiceBox – Text Controls – Scroll Pane.
Layouts – FlowPane – HBox and VBox – BorderPane –
StackPane – GridPane.
Menus – Basics – Menu– Menu bars – MenuItem
JAVAFX Events and Controls
JavaFX
● 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.
● intended to replace swing in Java applications as a GUI framework
● provides more functionalities than swing.
JavaFX Packages
● JavaFX framework is contained in packages that begin with the javafx
prefix
● E.g.
○ [Link], [Link], [Link], and [Link]
Setting the Stage with the Stage and Scene Classes
● a stage defines a space and a scene defines
what goes in that space
● a stage is a container for scenes and a scene
is a container for the items that comprise the
scene
● 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
import [Link];

import [Link];
Stage & Scene
● Stage [Link](scene);
○ 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.
● Scene
○ Scene is a container for the items that comprise the scene.
○ These can consist of various types of GUI elements, such as controls,
text, and graphics.
○ To create a scene, you will add elements to an instance of Scene.
Then, set that Scene on a Stage
Nodes and Scene Graphs
● elements of a scene are called nodes.
○ E.g. push button control is a node
● nodes can also consist of groups of nodes
● a node with a child is called a parent node or branch
node.
● Nodes without children are terminal nodes and are
called leaves.
● The collection of all nodes in a scene creates what is
referred to as a scene graph, which comprises a tree.
● one special type of node in the scene graph, called the
root node
○ top-level node and is the only node in the scene graph tree that
does not have a parent
● base class for all nodes is Node.
Lower-Bounded Wildcards (? super Type)
● Allows a type that is either a specific type or a supertype of it.
● Useful for writing data where you need to handle supertypes.
Layouts
● JavaFX provides several layout panes that manage the process of placing
elements in a scene
○ FlowPane class provides a flow layout
○ GridPane class supports a row/column grid-based layout
○ BorderPane, which organizes output within four border areas and a
center, are available
● Each inherits Node
● layouts are packaged in [Link].
The Application Class and the Life-Cycle Methods
● JavaFX application must be a subclass of the Application class, which is
packaged in [Link]
● your application class will extend Application
● Application class defines three life-cycle methods that your application
can override
● init( ), start( ), and stop( )
The Application Class and the Life-Cycle Methods
● init()
○ called when the application begins
execution
○ perform various initializations
○ it cannot, however, be used to create a
stage or build a scene
○ If no initializations are required, this
method need not be overridden because
an empty, default version is provided
The Application Class and the Life-Cycle Methods
● start()
○ start( ) method is called after init( )
○ where your application begins, and it can be used to construct
and set the scene
○ it is passed a reference to a Stage object
○ This is the stage provided by the run-time system and is the
primary stage
○ this method is abstract. Thus, it must be overridden by your
application.
● stop()
○ application is terminated
○ handle any cleanup or shutdown chores
Launching a JavaFX Application
● when a JavaFX application begins execution, an instance of the subclass of
Application defined by the application is created
● init( ), followed by start( ), is executed
● case of a free-standing, self-contained JavaFX application, a call to the
launch( ) method defined by Application may be needed
● launch( ) is included in all of the programs
Label
● displays a message or an image
● [Link]. Label
● Label(String str)
● Once created, it must be added to the scene’s content → add to scene
graph
● call getChildren( ) on the root node of the scene graph.
● returns a list of the child nodes in the form of an
ObservableList<Node>
● call add( ) on the list of child nodes
Event Basics
Event Basics
● Uses delegation event model approach to handle events.
● Source – > generates event —> sends to one or more listeners→ this
handles event
● To receive an event, the handler for the event must first be registered
with the event source.
● When the event occurs, the handler is called. It must then respond to the
event and return
Event Class
● base class for JavaFX events is the Event class
● [Link]. Event
EventHandler Interface
● Events are handled by implementing the EventHandler interface
● also in [Link]

● T specifies the type of event that the handler will handle


● defines one method, called handle( )

● eventObj is the event that was generated


Event Dispatch Chain
● In JavaFX, events are processed via an event dispatch
chain
● event dispatch chain is a path from the top element
in the scene graph (typically the stage) to the target
of the event, which is the control that generated the
event.
● When an event is processed, two main phases occur
a. the event is passed from the top element down
the chain to the target of the event. This is called
event capturing
b. After the target node processes the event, the
event is passed back up the chain, thus allowing
parent nodes a chance to process the event, if
required. This is called event bubbling
Introducing the Button Control
● To generate events, source of events is needed
● In JavaFX, the push button control is provided by the Button class
● [Link]
● Buttons can contain text, graphics, or both
Introducing the Button Control
● When a button is pressed, an ActionEvent is generated. ActionEvent is
packaged in [Link]
Handle Key and Mouse Events
Handle Key and Mouse Events
● Events from keyboard and mouse
Key Events
● When a key is typed on the keyboard, a KeyEvent is generated
● KeyEvents can be handled by both the Node and Scene classes
● When a key event is handled by a Node, events are received only when
that node has input focus.
● When a key event is handled by a Scene, events are received when the
scene has input focus.
● KeyEvent is packaged in [Link].
● three types of key events
○ KEY_PRESSED, KEY_RELEASED, and KEY_TYPED
Key Events

● When a key-typed event is received, you can obtain the character by


calling getCharacter( ) on the event.
● It is shown here:
Key Events
● getCharacter( ) should be used only for key-typed events
● For key-pressed and key-released events, KeyCode is used obtain the key
code associated with the event
Mouse Events
● Mouse events are represented by the MouseEvent class packaged in
[Link].
● An event is generated when the mouse is moved, when a button is clicked
or released, when the mouse enters or exits an element that handles
mouse events, or when the mouse is dragged
● Events:
○ MOUSE_CLICKED and
○ MOUSE_MOVED
Mouse Events

● When the mouse is clicked, getButton( ) finds out which button was used

● [Link] - left button was clicked


● [Link] - right button was clicked
● [Link] - mouse with a middle button
● [Link] - no button was clicked
Mouse Events
● getClickCount( ) - obtain the number of times a mouse button has been
clicked
● To obtain the location of the mouse at the time an event occurred
○ get its X,Y coordinates relative to the element
○ relative to the scene that contains the element or relative to the
screen
○ origin is the upper-left corner
JAVAFX Controls
Controls - CheckBox
● CheckBox encapsulates the functionality of a check box
● immediate superclass of CheckBox is ButtonBase
○ CheckBox represents a special type of button
● checked or unchecked, indeterminate
● CheckBox(String str)
Controls - CheckBox
● CheckBox generates an action event when it is clicked.
● set the action event handler on a CheckBox by calling setOnAction( ),
● obtain the state of a check box by calling isSelected( ).

● It returns true if the check box is selected and false otherwise


Controls - Toggle Button
Controls -Radio Button
Controls - ListView
// ListView
Label listviewlabel = new Label("Select list");

// Create an ObservableList of items for the ListView


ObservableList<String> items = [Link](
"Item 1", "Item 2", "Item 3", "Item 4", "Item 5");
ListView<String> lis = new ListView<>(items);
[Link](80, 80);
MultipleSelectionModel<String> selmodel = [Link]();
[Link]().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> changed, String
oldval, String newval) {
[Link](newval);
}
});
Controls - ListView - Multiple selection
Controls - Combo Box
Controls - Choice Box
Controls - Text Control
● Used to enter text
● user enter a string
○ used to obtain a filename, a search string, or an e-mail address.
● three forms of text controls
○ TextField - one line of text to be entered
○ TextArea - multiline text
○ PasswordField - used to input passwords because what is typed is not
shown.
● inherit TextInputControl
Controls - Text Control
● TextField tf1=new TextField(); – Syntax
● final void setPrefColumnCount(int columns)
○ specify a TextField’s size.
● final void setText(String str)
○ set the text in a text field
● final string getText( )
○ obtain the current text
● final void setPromptText(String str)
○ set a prompting message that is displayed inside the text field
when the user attempts to use a blank field.
● getCaretPosition( ) - returns the current position of the caret (the
blinking cursor) inside the TextField
● getAnchor( ) - position of the anchor in the selection
Controls - Scroll Pane
● UI controls need by automatic
adding scroll bars when their
contents exceed their dimensions.
● ScrollPane - provide scrolling
capabilities to any node in a scene
graph.
● When a ScrollPane is used, scroll
bars are automatically implemented
that scroll the contents of the
wrapped node.
● ScrollPane(Node content)
○ content specifies the information to be
scrolled.
Controls - ScrollPane
● final void setContent(Node content)
○ add the scroll pane to the scene graph.
● viewport is the viewable area of a scroll pane.
○ area in which the content being scrolled is displayed.
○ final void setPrefViewportHeight(double height)
○ final void setPrefViewportWidth(double width)
● getPrefViewportHeight( ) and getPrefViewportWidth( ) - obtain the current viewport
height and width
● ScrollPane offers the ability to pan its contents by dragging the mouse. By
default, this feature is off. To turn it on, use setPannable( )
○ final void setPannable(boolean enable)
Controls - ScrollPane
● [Link](1) & [Link](0);
○ attempt to scroll the content.
○ Vvalue and Hvalue should be in the range [0, 1],
○ where:
■ 0 represents the top/left of the content.
■ 1 represents the bottom/right of the content.
JAVAFX Layouts
Layouts
● Arrangement of controls or components inside the scene is called layout
● JavaFX class that manages the layout is called Layout Managaer
● packaged in [Link]
FlowPane
● FlowPane lays out content line by line
● By default, a horizontal flow is used,
possible for vertical flow also
● wrap length - length at which the next
element will be wrapped to the next
line.
● setHgap(Double value) - Horizontal gap
between the columns.
● setVgap(Double value) - The vertical gap The preferred height or width
among the rows where content should wrap in the
horizontal or vertical flowpane.
HBox and VBox
● HBox organizes its contents into a horizontal line.
● VBox lays out its contents in a vertical column.
● Advantage:
○ contents will not be reorganized when the pane’s size is changed.
● Constructors
○ hGap specifies the horizontal space between elements
○ vGap specifies the vertical gap.
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
HBox root = new HBox();
Scene scene = new Scene(root,200,200);
[Link]().addAll(btn1,btn2);
[Link](40);
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
VBox root = new VBox();
Scene scene = new Scene(root,200,200);
[Link]().addAll(btn1,btn2);
BorderPane
● It implements a layout style that
defines five locations to which
an item can be added.
● The first is the center.
● The other four are the sides (i.e.,
borders): top, bottom, left, and
right. BorderPane() : create the empty layout
● 5 methods - setRight(), setLeft(), BorderPane(Node Center) : create the layout
setCenter(), setBottom() and with the center node
setTop( BorderPane(Node Center, Node top, Node
right, Node bottom, Node left) : create the
layout with all the nodes
Border Pane
● static void setAlignment(Node what, Pos how)
○ set the alignment used in a location
○ what specifies the element being aligned
○ how specifies the alignment.
○ Pos is an enumeration that specifies alignment constants, such as
[Link], Pos.BOTTOM_RIGHT, and Pos.TOP_LEFT. It is packaged
in [Link].
BorderPane BPane = new BorderPane();
[Link](new Label("This will be at the top"));
[Link](new Label("This will be at the left"));
[Link](new Label("This will be at the Right"));
[Link](new Label("This will be at the Centre"));
[Link](new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
StackPane
● StackPane layout pane places all the nodes into a single
stack
● where every new node gets placed on the top of the
previous node
● useful when you want to overlay one control with
another.
● The class contains two constructors that are given
below.
○ StackPane()
○ StackPane(Node? Children)
● setAlignment(Node child, Pos value) - default alignment
of children within the StackPane's width and height
Button btn1 = new Button("Button 1 on bottom ");
Button btn2 = new Button("Button 2 on top");
StackPane root = new StackPane();
Scene scene = new Scene(root,200,200);
[Link]().addAll(btn1,btn2);
[Link](scene);
[Link]();
GridPane
● allows us to add the multiple nodes in multiple rows and columns.
● seen as a flexible grid of rows and columns where nodes can be placed in
any cell of the grid.
● gives you a way to position controls at specific locations within a
two-dimensional grid.
● location at which a child node is added to the grid
○ static void setConstraints(Node what, int column, int row)
○ setRowIndex( ) and setColumnIndex( ).
○ void add(Node child, int column, int row)
● set the vertical or horizontal gap around a control
○ final void setVgap(double gap)
○ final void setHgap(double gap)
Menus
Menus
● JavaFX provides a Menu class to
implement menus
● Menu is the main component of a any
application
● [Link]
MenuBar
● a container for menus.
● control that supplies the main menu of
an application.
● getMenus( ) - It returns a list of the
menus managed by the menu bar.
● final ObservableList<Menu> getMenus( )
● void add(int idx, Menu menu)
○ Menu instance is added to this list
of menus
Menu
● populated with MenuItems
● Constructors
○ Menu(String name)
○ Menu(String name, Node image)
● setText( ) or setGraphic( ) - add or
change a name and/or image
● Each menu maintains a list of menu
● add( ) or addAll( ) - add menu
items that it contains.
items
● final ObservableList<MenuItem>
● remove an item by calling
getItems( ) - returns the list of items
remove( )
currently associated with the menu.
● obtain the size of the list by
calling size( ).
MenuItem
● MenuItem encapsulates an element in a
menu.
● can either be a selection linked to some
program action
● Constructors
○ MenuItem( )
MenuItem(String name)

● add( ) or addAll( ) - add menu
○ MenuItem(String name, Node image)
items
● A MenuItem generates an action event
● remove an item by calling
when selected - setOnAction( )
remove( )
● final void setDisable(boolean disable) -
● obtain the size of the list by
enable or disable a menu item.
calling size( ).

You might also like