[Go to site: main page, start]

0% found this document useful (0 votes)
9 views75 pages

Java Programming Chapter-3 JavaFX

Chapter Three provides an overview of JavaFX, a modern GUI framework for building interactive applications. It distinguishes JavaFX from AWT and Swing, outlines the lifecycle of a JavaFX application, and covers key concepts such as layout panes, event handling, and CSS styling. The chapter also includes practical steps for creating JavaFX applications and utilizing various GUI controls.

Uploaded by

birukasefa205
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)
9 views75 pages

Java Programming Chapter-3 JavaFX

Chapter Three provides an overview of JavaFX, a modern GUI framework for building interactive applications. It distinguishes JavaFX from AWT and Swing, outlines the lifecycle of a JavaFX application, and covers key concepts such as layout panes, event handling, and CSS styling. The chapter also includes practical steps for creating JavaFX applications and utilizing various GUI controls.

Uploaded by

birukasefa205
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

Ch ap t e r T h ree

J a v a GUI u s i n g JAVAFX
Obj ectives
• To Describe JavaFX

• To distinguish between JavaFX , Swing, and AW T

• To Describe the life cycle of a JavaFX application

• To Recognize JavaFX structure: stage, scene, and widgets

• To Write an application using JavaFX

• To Create JavaFX applications using Scene Builder

• To Use CSS to create visual effects

• To layout nodes using Pane, StackPane, FlowPane, GridPane, Border Pane, HBox,

and VBox.

• To display text using the Text class and create shapes using Line, Circle,

Rectangle, Ellipse, Arc, Polygon, and Polyline


Introductio n
•GUI provides a user-friendly way to interact with
applications.
•Enhances an application’s look and feel.
•Ensures consistency and familiarity, helping users:
• Learn new applications faster
• Navigate easily
• Work efficiently
•GUIs is simply the plural form of GUI, meaning multiple graphical
user interfaces
•GUIs are built from components (also called controls or
widgets)

•GUI components are objects that users interact with via:


• Mouse
• Keyboard
• Other input methods (e.g., voice recognition)
Introductio n
Java Has Three Main GUI Packages
•Java provides libraries for building Graphical User
Interfaces (GUIs).
•The three main GUI packages are:
[Link] (Abstract Window Toolkit)
[Link]
[Link]
AWT vs S-wing vs JavaFx

1. AWT (Abstract Window Toolkit)


•Definition: Java’s original GUI toolkit, part of [Link] package.
•Key Features:
•Uses native OS components (heavyweight components).
•Basic GUI components: Button, Label, TextField, Frame.
•Limited look-and-feel customization.
•Pros:
•Simple for basic GUI.
•Platform-independent code runs on any OS.
•Cons:
•Limited components and functionality.
•UI looks different on different OS (native-dependent).
AWT vs S-wing vs JavaFx

Swing
•Advanced GUI toolkit built on top of AWT, part of [Link]
package.
•Key Features:
•Lightweight components (not tied to native OS).
•Richer set of components: JButton, JLabel, JTable, JTree,
JTabbedPane.
•Supports custom look-and-feel.
•Event handling via ActionListener, MouseListener, etc.
•Pros:
•Highly customizable GUI.
•Consistent look across platforms.
•Cons:
•Slightly slower than AWT (because of lightweight
components).
•More complex for beginners.
AWT vs Sw i n g vs Java Fx

• Swing is built "on top of " AW T, so you need to impor t AW T and


use a few things from it
• Swing is bigger and slower
• Swing is more flexible and better looking
• Swing and AW T are in co mpatible- -you can use either, but
you can 't mix them
• Actually, you can, but it 's tricky and not wor th doing
• Basic components / controls are practically the same in both
• AWT: Button b = new Button ("OK ") ;
• Swing: ] Button b = new JButton(" OK ");
• Swing gives far m ore options for everything (buttons with
pictures on them , etc.)
• AW T classes are contained inside package j a v a . a w t while
swing classes are located in package j a v a x . s w i n g .
AWT VS SWING
• AWT features include:

• A rich set of user interface components.


• A robust event-handling model.
• Graphics and imaging tools, including shape, color, and font classes.
• Swing features include :

• All the features of AW T.


• 1OO% Pur e Java cer tified versions of th e existing AW T compon ent set
• A rich set of higher-level components (such as tree view, list box, and
tabbed panes) .
• Pur e Java design, no r eliance on p eers .
• Pluggable Look and Feel.
SWING GUI CLASS

1. GUI API Or GUI Class (Graphical User Interface


Application Programming Interface) allows developers to
create windows, buttons, text fields, and other
interactive elements in Java applications.

2. Java’s GUI classes are grouped into three main


categories:
• Container Classes
• Component Classes
• Helper (or Utility) Classes
SWING GUI CLASS

1. Container Classes
Used to hold and organize Swing components.
They form the structure of the GUI.

Common Swing Containers:


•JFrame – Main window
•JPanel – General-purpose container
•JDialog – Pop-up dialog box
•JApplet – Applet window (old)
GUI CLASS

2 Component Classes
Represent visible GUI elements that users interact
with.
All Swing components inherit from JComponent.
Examples:
• JButton – clickable button
• JLabel – display text or image
• JTextField, JTextArea – text input
• JCheckBox, JRadioButton – selection controls
• JList, JComboBox, JTable, JTree – data display
components
GUI CLASS

3. Helper / Utility Classes


Provide support functions for event handling, layout,
look-and-feel, etc.
Examples:
• LayoutManager classes – BorderLayout, FlowLayout,
• GridLayout
• Event classes – ActionEvent, MouseEvent, etc.
• Listener interfaces – ActionListener, MouseListener, etc.
• Border, Color, Font, ToolTipManager, UIManager – for styling
and control
JavaFX
Rich GUI Framework:
Develop interactive and visually appealing applications.
Cross-Platform:
Runs on desktop and web browsers seamlessly.
Rich Internet Applications (RIA):
Web apps with desktop-like features and functionality.
Multi-Touch Support:
Works on tablets and smartphones.
Multimedia Support:
Built-in 2D & 3D graphics, animations, video, and audio.
Flexible Deployment:
Can run as standalone apps or in-browser applications.
Modern Look & Feel:
Supports CSS styling and FXML for clean, maintainable UI design.
Cont ..'
Why Java GUI programmin g using JavaFX?

•Easy to Learn:
Simpler for new Java programmers compared to older GUI libraries.
•Modern Replacement:
Designed to replace Swing, which is no longer actively enhanced.
•Cross-Platform:
Run applications on Windows, Linux, iOS, Android, desktops, web,
TVs, and tablets.
•Rich GUI & Multimedia:
Supports 2D/3D graphics, animations, video, and audio.
•Hardware Accelerated & Lightweight:
Efficient performance with modern hardware.
•Flexible Deployment: Build applications for desktop, web, and
handheld devices.
XML-based markup for defining JavaFX UI
layout.
Separates UI design (FXML) from logic
(Controller).
•Features:
•Declarative UI: buttons, labels, layouts
in XML
•Controller linkage: handle events in Java
code

Benefits:
•Cleaner, maintainable code
•Follows MVC pattern
•Faster UI development
Life Cycle of a JavaFX Application

1. Initialization (init() method)


• Called once when the application [Link] for
non-GUI setup (e.g., loading data, initializing
variables).Runs before the GUI is created.

2 .Start (start(Stage primaryStage) method)


• Called after [Link] main entry point for all
JavaFX GUI code.
• You create the Stage, Scene, and UI elements here.
• The application’s main window appears.
Life Cycle of a JavaFX Application

[Link] (Event Handling & User Interaction)


The application stays active while the window is
open. JavaFX event loop manages user actions,
animations, and updates.
[Link] (stop() method)
Called when the application is about to [Link]
forcleanup tasks (e.g., saving data, closing files).
launch(args) → Starts the JavaFX runtime, which calls init(), start(), and later
stop() automatically.

JavaFX follows a simple lifecycle:


👉 launch() → init() → start() → running → stop()
Steps for Creating a JavaFX Application
1. Import JavaFX Packages
Import the necessary JavaFX libraries.
import [Link];
import [Link]; I
mport [Link];
import [Link];
import [Link];
2. Extend the Application Class
•Every JavaFX application must extend the Application class.
public class MyApp extends Application
{

}
3 Override the start() Method
•The entry point of the JavaFX app.
•Sets up the Stage (window) and Scene (content).

public class MyApp extends Application


{
@Override
public void start(Stage primaryStage)
{ // GUI logic goes here

}
}
[Link] UI Components
•Use controls like Button, Label, TextField, etc.
Label label = new Label("Hello, JavaFX!");

5. Create a Layout Pane


•Layout panes (like StackPane, VBox, BorderPane)
organize UI components.
StackPane root = new StackPane();
[Link]().add(label);
[Link] a Scene
•A Scene holds all the visual elements.
Scene scene = new Scene(root, 300, 200);
[Link] UI Components
•Use controls like Button, Label, TextField, etc.
Label label = new Label("Hello, JavaFX!");

5. Create a Layout Pane


•Layout panes (like StackPane, VBox, BorderPane)
organize UI components.
StackPane root = new StackPane();
[Link]().add(label);
[Link] a Scene
•A Scene holds all the visual elements.
Scene scene = new Scene(root, 300, 200);
7 Set the Scene on the Stage
•Attach the Scene to the Stage and make it visibl
[Link](scene);
[Link]("My First JavaFX App");
[Link]();
8. Launch the Application
•The launch(args) method starts the JavaFX runtime
public static void main(String[] args)
{
launch(args);
}
Layout panes in JavaFX
•Layout panes in JavaFX manage the position and
size of UI controls.
•They help create responsive and organized user
interfaces.
•Commonly used layout panes include:
•HBox – Arranges nodes horizontally.
•VBox – Arranges nodes vertically.
•BorderPane – Divides layout into top, bottom,
left, right, center regions.
Layout panes in JavaFX

•GridPane – Places nodes in a grid of rows and


columns.
•StackPane – Stacks nodes on top of each other.
•FlowPane – Arranges nodes in a flow, wrapping
at boundaries.
•AnchorPane – Positions nodes by fixed anchors
on edges.
•Each pane adjusts layout automatically when
window size changes.
•Layout panes can be nested for complex designs.
JavaFX Event Handling

Event handling is the mechanism to control user actions


like clicks, key presses, and mouse movements.
Three Main Parts of Event Handling in JavaFX

Event Source: The component that generates the event


(e.g., Button, TextField).
Event Object: Carries details about the event (e.g.,
ActionEvent, MouseEvent).
Event Handler: The block of code that executes when an
event [Link] uses the Event Handling API to
manage these interactions.
JavaFX Event Handling
Event handlers can be added using: Lambda expressions
and Event Handler Interface
[Link] expressions

2. Implementing EventHandler Interface


Common Event Types in JavaFX

• Action Event – Triggered by actions like button


clicks or menu selections.
• Mouse Event – Occurs when the user interacts
with the mouse (click, drag, move, scroll).
• Key Event – triggered when a key is pressed or
released on the keyboard.
• Input Event – Represents general input from the
user including keyboard and mouse.
• Window Event – Related to window operations
such as opening, closing, or resizing.
Javafx Shapes
JavaFX provides the [Link] package
that contains classes for drawing 2D geometric
shapes such as lines, rectangles, circles, and
polygons
.All shape classes inherit from the Shape class,
which itself is a subclass of Node (so shapes can be
added to a Scene Graph).
Commonshapes

• Common Shape Classes:


• Line – Draws a straight line between two points.
• Rectangle – Draws a rectangle or square.
• Circle – Draws a circle with a specified center and radius.
• Ellipse – Draws an oval shape.
• Polygon – Draws a closed multi-sided shape using
coordinate points.
• Polyline – Similar to Polygon, but open (not closed).
• Arc – Draws part of a circle or ellipse.
• QuadCurve / CubicCurve – Draws smooth curved lines.
Java FX Cascading Style Sheets (CSS)
•JavaFX supports Cascading Style Sheets (CSS) to style UI
components.
•It allows you to separate design (style) from logic (code).
•Similar to web CSS, it controls colors, fonts, padding, borders,
etc.
•Makes UI consistent, customizable, and maintainable.
Common Event Types in JavaFX
Three Main Parts of a Style Rule:
[Link] – Specifies which component(s) the style applies to
•Type selector: Button { } → all buttons
•Class selector: .my-class { } → components with this class
•ID selector: #my-id { } → a specific component
[Link] – Defines what aspect of the component to style
•Examples: -fx-background-color, -fx-text-fill, -fx-font-size, -fx-
font-family
[Link] – The actual style applied to the property
•Examples: #3498db, white, 16px, "Arial"
Ways to Apply CSS in JavaFX
[Link] CSS File
•Define styles in a separate .css file
(e.g., [Link]).
•Makes your UI design independent from
code (recommended).
•Add the CSS file to your scene or parent
node.
Example (CSS file: [Link]):
.label {
-fx-text-fill: darkblue; -fx-font-
size: 18px;
Ways to Apply CSS in JavaFX

2 Inline Style (using setStyle())


•Apply CSS directly to a component in Java
code.
•Quick but not reusable.
Example:
Button btn = new Button("Click Me");
[Link]("-fx-background-color:
lightgreen; -fx-font-size: 14px;");
JAVA FX CSS

JavaFX CSS – Using setStyle()


Definition:
•setStyle() allows you to apply CSS
styles directly to a JavaFX component in
code without using an external .css file.
•Useful for quick styling or dynamic styles at
runtime.
Basic GUI Controls in Java FX
1 .Button ([Link])
Common Methods Used In Butons
Method Description
Sets the text displayed on the
setText(String text)
button.
getText() Returns the button text.
setOnAction(EventHandler<Act
Handles click events.
ionEvent> event)

setDisable(boolean value) Enables or disables the button.

setStyle(String style) Adds CSS styling.

setId(String id) Sets an ID to reference in CSS.


Basic GUI Controls in Java FX
[Link] ([Link])
Common Methods Used In Labels
Method Description
setText(String text) Sets the label text.
getText() Returns the text of the label.
setFont(Font font) Sets the font size/style.
setTextFill(Paint color) Changes the text color.
setAlignment(Pos pos) Aligns text within label.
setWrapText(boolean value) Wraps text if it's too long.
Basic GUI Controls in Java FX
3. TextField ([Link])
Common Methods Used In TextFields

Method Description

setText(String text) Sets the initial text.


Returns text entered by
getText()
user.
clear() Clears the text.

setPromptText(String text) Placeholder text.

setEditable(boolean value) Enable or disable editing.


Basic GUI Controls in Java FX
4. CheckBox([Link])

Method Description

setSelected(boolean value) Checks/unchecks the box.

isSelected() Returns true if checked.

Sets label text for the


setText(String text)
checkbox.

setOnAction(EventHandler<Ac
Handles click events.
tionEvent> event)
End of chapter 3

You might also like