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

JavaFX

The document provides an overview of JavaFX, a graphics and media package for developing rich client applications in Java. It covers key concepts such as stages, scenes, nodes, UI controls, event handling, and property binding, along with examples of creating a simple JavaFX application. Additionally, it discusses various layout panes and customization options for colors and fonts in JavaFX applications.

Uploaded by

favshah1206
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JavaFX

The document provides an overview of JavaFX, a graphics and media package for developing rich client applications in Java. It covers key concepts such as stages, scenes, nodes, UI controls, event handling, and property binding, along with examples of creating a simple JavaFX application. Additionally, it discusses various layout panes and customization options for colors and fonts in JavaFX applications.

Uploaded by

favshah1206
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Index

4.1 Basics of JAVAFX ....................................................................................... 2


4.2 Panes in JavaFX ........................................................................................... 8
4.3 UI Controls and Shapes in JavaFX ............................................................. 11
4.4 Property Binding in JavaFX........................................................................ 13
4.5 Color and Font Class in JavaFX.................................................................. 14
4.6 Image and ImageView Class in JavaFX ...................................................... 16
4.7 Events and Event Sources in JavaFX .......................................................... 17
4.8 Inner Classes and Anonymous Inner Class Handlers in JavaFX .................. 21
4.9 Handling Mouse and Key Events in JavaFX .............................................. 22
4.10 Listeners for Observable Objects in JavaFX ............................................. 23
4.11 Animation in JavaFX ................................................................................ 24
5.1 JavaFX UI Controls .................................................................................... 26
1.Button ..................................................................................................... 28
2. Checkbox ............................................................................................... 28
3. RadioButton ........................................................................................... 28
4. TextField ................................................................................................ 29
5. TextArea ................................................................................................ 29
6. ComboBox ............................................................................................. 30
7. ListView ................................................................................................ 30
8. Scrollbar ................................................................................................. 31
9. Slider...................................................................................................... 31
10. Video and Audio (MediaPlayer) ........................................................... 31

1
UNIT 4
JavaFx Basics and Event-driven programming and
animations

4.1 Basics of JAVAFX


• JavaFX was originally developed by Chris Oliver, when he was working for a company named
See Beyond Technology Corporation, which was later acquired by Sun Microsystems in the
year 2005.

• JavaFX is a set of graphics and media packages that enables developers to design, create,
test, debug, and deploy rich client applications that operate consistently across different
platforms.

• JavaFX makes it easier to create desktop applications

and Games in Java.

• JavaFX has replaced Swing as the recommended GUI toolkit for Java. Furthermore, JavaFX
is more consistent in its design than Swing, and has more features.

Features of JAVAFX

1) JavaFX library is written in java. Hence developer find it easy to learn and write the
applications in JAVAFX.

2) JAVAFX library creates UI controls using which any GUI based application can be
developed.

3) It provides the classes for 2D and 3D graphics.

4) JavaFX contains a set of ready-to-use chart components, so you don't have to code
that from scratch every time you need a basic chart.

5) JavaFX components can be styled using CSS.

6) It provides the support for integrating audio, videos, and web applications.

We need to import javafx.application.Application class in every JavaFX application.

Every JAVAFX program is divided into three main components - Stage, Scene and Node and
Scene graph.

2
(1) Stage; Stage is like main frame of the program. It acts as a container for all the objects of
JavaFX application. The most commonly used stage is a PrimaryStage. It is created internally
by the platform. The object of PrimaryStage is passed to the start() method. There is a show
method that is used to show the stage.

(2) Scene: The Javafx.scene.Scene class provides the methods to deal with the scene object.
It contains the nodes or all the contents of Scene graph. The scene is created by instantiating
the Scene class.

(3) Scene Graph and Node: The scene graph is a collection of various nodes. The node is an
element that can be visualized on the screen. The node can be button, textbox, radio button
and so on.

The nodes are implemented in tree like manner. There is one root node. This will be
the parent node of all the other nodes.

Important Methods used in JavaFX Application

(1) start(): This is the method in which we write the code for JavaFX application. The
construct for this method is

public abstract void start(Stage primaryStage)

(2) launch() 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. Since the
launch() method is static, you need to call it from a static method such as main()

3
 Writing First JavaFX Application Program

We can create an application program in NetBean IDE or Eclipse IDE. Following steps are
used to create this application program -

Prerequisite: Before executing the JavaFX application program, you need to have following
things installed in your PC

i) Java 8

ii) NetBeans 8

Step 1: From the File menu, choose New Project. Then select JavaFX application category,
choose JavaFX Application. Click Next.

4
Then the code can be written as follows

package myjavafxapplication;

import javafx.application.Application;

5
import static javafx.application. Application.launch;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage) {

Label L= new Label(" WELCOME TO FIRST APPLICATION USING JAVAFX");

Scene scene = new Scene(L, 300, 300);

primaryStage.setTitle("FIRST DEMO PROGRAM");

primaryStage.setScene(scene);

primaryStage.show();

}
public static void main(String[] args) {

launch(args);

Step 2: Now right click on the source file and click on Run File As. The output will be
displayed as follows

Output

Program Explanation: In above program,


6
1. We have to import javafx.application.Application package to support the Application class.

2. Then we need to import the classes for supporting - Stage Scene, Label component
and launch method. Hence we add following lines in our code.

import static javafx.application. Application.launch;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.stage.Stage;

3. Our class must extend Application class.

4. Then we write overridden start() method in which the entire application code is written.
The primaryStage is passed as a framework to this start method as a parameter. Note that
these are all standard steps for any JavaFX application program.

5. Then we have -

Step 1: Created a Label component.

Label L=new Label(" WELCOME TO FIRST APPLICATION USING JAVAFX");

Step 2:Created a Scene using new operator and placed the Label component on Scene.
Scene scene = new Scene(L, 300, 300);

Step 3: Using setScene method we have set this scene for Stage

primaryStage.setScene(scene);

Step 4: If you want to display the title for your application page, then it is possible by using
setTitle method for the Stage component. Keep it in mind that here stage is something like a
frame on which scene, UI components are placed.

primaryStage.setTitle("FIRST DEMO PROGRAM");

Step 5: Finally any component can be made visible by using show() method.

primaryStage.show();

6. Then write the main() method which in turn will call launch() method to call your start()
method.

public static void main(String[] args) {

launch(args);
7
}

That's it. Now run your application program and a Label component with some message will
be displayed as an output.

4.2 Panes in JavaFX


In JavaFX, panes are layout containers that help organize UI components in a structured
manner.
Different types of panes are available to position elements efficiently.

1. StackPane

 Places all children stacked on top of each other.


 Aligns them in the center by default.

Example:
StackPane stackPane = new StackPane();
stackPane.getChildren().add(new Button("Click Me"));

2. FlowPane

 Arranges children in a row or column.


 Automatically wraps elements to the next line.

Example:
FlowPane flowPane = new FlowPane();
flowPane.getChildren().addAll(new Button("1"), new Button("2"), new Button("3"));

8
3. GridPane

 Arranges children in a grid (rows and columns).

Example:
GridPane gridPane = new GridPane();
gridPane.add(new Button("Button 1"), 0, 0); // Column 0, Row 0
gridPane.add(new Button("Button 2"), 1, 0); // Column 1, Row 0
gridPane.add(new Button("Button 3"), 0, 1); // Column 0, Row 1

4. BorderPane

 Divides the scene into top, bottom, left, right, and center regions.

Example:

9
BorderPane borderPane = new BorderPane();
borderPane.setTop(new Label("Top"));
borderPane.setCenter(new Button("Center"));
borderPane.setBottom(new Label("Bottom"));

5. VBox (Vertical Box)

 Arranges children in a vertical column.

Example:
VBox vbox = new VBox(10); // Spacing of 10
vbox.getChildren().addAll(new Button("A"), new Button("B");

6. HBox (Horizontal Box)

 Arranges children in a horizontal row.

Example:
HBox hbox = new HBox(10);

10
hbox.getChildren().addAll(new Button("X"), new Button("Y"));

7. AnchorPane

 Allows precise positioning using anchors.

Example:
AnchorPane anchorPane = new AnchorPane();
Button btn = new Button("Anchored");
AnchorPane.setTopAnchor(btn, 10.0);
anchorPane.getChildren().add(btn);

Choosing the Right Pane

Pane Best for


StackPane Centered content, overlays
FlowPane Wrapping layouts
GridPane Forms, tables
BorderPane Header, sidebar layouts
VBox Vertical alignment
HBox Horizontal alignment
AnchorPane Custom positioning

4.3 UI Controls and Shapes in JavaFX


JavaFX provides a variety of UI controls (buttons, text fields, labels, etc.) and shapes
(rectangles, circles, lines, etc.) to build interactive applications.

1. UI Controls

UI controls are components that allow user interaction.

11
Common UI Controls in JavaFX

Control Description
Label Displays text or images

Button Triggers an action

TextField Allows single-line text input

TextArea Allows multi-line text input


CheckBox Allows selection/deselection

RadioButton Part of a group where one can be selected

ComboBox Dropdown list for selection

ListView Displays a list of items

TableView Displays tabular data


Slider Allows numeric selection using a slider

2. Shapes in JavaFX

JavaFX provides various 2D shapes for drawing graphics.

Common Shapes in JavaFX

Shape Description

Line A straight line between two points

Rectangle A rectangular shape

Circle A circular shape

Ellipse An oval shape

Polygon A shape with multiple points

Polyline A series of connected lines

Arc A curved shape

12
4.4 Property Binding in JavaFX
Property Binding in JavaFX allows one UI component’s property to be automatically updated
when another property changes. This ensures synchronization without manually handling
updates.

1. Types of Property Binding

JavaFX provides two ways to bind properties:

1.1 Unidirectional Binding

 One property is bound to another.


 The bound property automatically updates when the source property changes.

1.2 Bidirectional Binding

 Two properties are bound to each other.


 Changes in either property affect the other.

2. Using Bindings for Computation

JavaFX allows binding expressions for computed values.

3. Property Binding with UI Controls

JavaFX properties allow binding UI elements like sliders and progress bars.

13
4. When to Use Property Binding?

Use Case Binding Type


Updating a label with user input
Unidirectional (bind())
Keeping two text fields in sync Bidirectional (bindBidirectional())
Auto-updating computed values Bindings (add(), multiply())
Connecting UI controls like sliders &
progress bars bind()

4.5 Color and Font Class in JavaFX


JavaFX provides the Color and Font classes to customize UI components with different colors
and fonts.

1. Color Class

The javafx.scene.paint.Color class is used to define colors in JavaFX.

1.1 Creating Colors

You can create colors using:

 Predefined Colors (Color.RED, Color.BLUE, etc.)


 RGB Values (Color.rgb(255, 0, 0))
 RGBA (With Opacity) (Color.rgb(255, 0, 0, 0.5))
 HSL (Hue, Saturation, Lightness) (Color.hsb(0, 100, 50))
 Hex Codes (Color.web("#ff0000"))

14
1.3 Using Colors in UI Controls

You can apply colors to UI elements like labels, buttons, etc. using setStyle().

label.setStyle("-fx-text-fill: blue;"); // Sets text color to blue


button.setStyle("-fx-background-color: #ff5733;"); // Sets button background color

2. Font Class

The javafx.scene.text.Font class defines fonts for UI elements.

2.1 Creating Fonts

Fonts can be created using:

 Default Font (Font.getDefault())


 Named Font (Font.font("Arial"))
 Font with Size (Font.font("Verdana", 18))
 Bold/Italic Font (Font.font("Times New Roman", FontWeight.BOLD,
FontPosture.ITALIC, 20))

2.2 Using Fonts in CSS

Instead of Java code, you can set fonts using CSS styles:

.label {
-fx-font-family: "Times New Roman";
-fx-font-size: 20px;
-fx-font-weight: bold;
}

Apply it in Java:

label.setStyle("-fx-font-size: 20px; -fx-font-family: 'Times New Roman'; -fx-font-weight:


bold;");

Combining Colors and Fonts in a JavaFX UI When to Use Color and Font?
Use Case Class
Setting text color Color (setTextFill())
Changing background color Color (setStyle("-fx-background- color: color;"))

Customizing fonts Font (setFont())


Making UI elements stylish
Both Color and Font

15
4.6 Image and ImageView Class in JavaFX
JavaFX provides the Image and ImageView classes to work with images in GUI applications.

. Image Class

The javafx.scene.image.Image class represents an image file (PNG, JPG, BMP, etc.). It loads
an image from a file, a URL, or an input stream.

Creating an Image

import javafx.scene.image.Image;
// Loading an image from a file Image img1 = new
Image("file:src/images/sample.png");
// Loading an image from a URL Image img2 = new
Image("https://example.com/sample.jpg");
// Loading an image from input stream (useful for resources inside JAR)
InputStream stream = getClass().getResourceAsStream("/images/sample.png"
);
Image img3 = new Image(stream);

ImageView Class

The javafx.scene.image.ImageView class is used to display an image in a JavaFX application.

ImageView Properties and Methods

Method Description
Sets the width of the image view.
setFitWidth(double width)
Sets the height of the image view.
setFitHeight(double height)
setPreserveRatio(boolean value) Keeps the aspect ratio of the image.
Applies smoothing for high-quality
setSmooth(boolean value) rendering.
Rotates the image by the given angle.
setRotate(double angle)
Sets the transparency (0 = invisible, 1 = fully
setOpacity(double value) visible).

16
4.7 Events and Event Sources in JavaFX

What is an Event in JavaFX?

An event in JavaFX is an action that occurs when the user interacts with a GUI component,
such as:

 Clicking a button ç'


 Moving the mouse ● ◉

 Pressing a key İîI

JavaFX follows the event-driven programming model, where event listeners handle event
sources.

Event Sources in JavaFX

An event source is any GUI component that can generate events.


Some common event sources:

Event Source Example


Button Clicking a button
TextField Typing in a text field
Scene Clicking anywhere on the window
Stage Window resizing, closing
Mouse Moving or clicking the mouse
Keyboard Pressing keys

Handling Events in JavaFX

There are 3 ways to handle events in JavaFX:

1. Using Lambda Expressions (Recommended)


2. Using an Anonymous Inner Class
3. Using a Separate Event Handler Class

Handling a Button Click Event

(1) Using a Lambda Expression (Best Practice)

Lambda expressions in JavaFX are a shorter and clearer way to write code for handling
events, like button clicks, without needing to create long, anonymous classes.

17
For example, instead of writing this:

button.setOnAction(new EventHandler<ActionEvent>() {

@Override

public void handle(ActionEvent event) {

System.out.println("Button clicked!");

});

You can use a lambda expression:

button.setOnAction(event -> System.out.println("Button clicked!"));

It makes the code cleaner, easier to read, and more concise,


especially when working with event handling in JavaFX.

Example:

import javafx.application.Application;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ButtonEventExample extends Application


{
@Override
public void start(Stage primaryStage)
{
Button btn = new Button("Click Me");

// Lambda Expression for Event Handling

btn.setOnAction(event ->System.out.println("Button Clicked!"));

StackPane root = new StackPane(btn);


Scene scene = new Scene(root, 300, 200);

primaryStage.setTitle("Button Event Example");


primaryStage.setScene(scene);

primaryStage.show();
}
public static void main(String[] args)
{
18
launch(args);
}
}

(2) Using an Anonymous Inner Class

btn.setOnAction(new EventHandler<ActionEvent>()

@Override
public void handle(ActionEvent event)
{
System.out.println("Button Clicked!");
}
});

(3) Using a Separate Event Handler Class

import javafx.event.ActionEvent; import


javafx.event.EventHandler;

public class ButtonClickHandler implements EventHandler<ActionEvent>


{
@Override
public void handle(ActionEvent event)
{
System.out.println("Button Clicked!");
}
}
Then, in the main class: btn.setOnAction(new ButtonClickHandler());

Different Types of Events

JavaFX provides different types of events, including:

1 Action Events (ActionEvent)

Triggered by buttons, menu items, and text fields (when pressing Enter).

btn.setOnAction(event -> System.out.println("Action Event Triggered!"));

2 Mouse Events (MouseEvent)

Triggered by mouse clicks, movements, and drags.

btn.setOnMouseEntered(event -> btn.setText("Mouse Over"));


btn.setOnMouseExited(event -> btn.setText("Click Me"));

19
3 Key Events (KeyEvent)

Triggered when a key is pressed, released, or typed.

scene.setOnKeyPressed(event ->
System.out.println("KeyPressed:" + event.getCode()));

4 Window Events (WindowEvent)

Triggered when the window is opened, closed, minimized, or resized.

primaryStage.setOnCloseRequest(event -> System.out.println("Window is closing..."));

Event Propagation (Bubbling & Capturing)

JavaFX events propagate through a hierarchy of nodes.

1 Event Bubbling

 The event moves from the target node up to the root.


 Example: Clicking a Button inside a VBox also triggers the VBox event.

vbox.setOnMouseClicked(event -> System.out.println("VBox Clicked!"));


btn.setOnMouseClicked(event -> System.out.println("Button Clicked!"));

2 Event Capturing

 The event moves from the root down to the target node.
 To capture an event before it reaches the target, use addEventFilter:

scene.addEventFilter(MouseEvent.MOUSE_CLICKE D, event -> System.out.println("Event


Captured!"));

Summary
Event Type Example
ActionEvent Button Click, TextField Enter
MouseEvent Click, Move, Hover
KeyEvent Press, Release, Type
WindowEvent Open, Close, Minimize

20
4.8 Inner Classes and Anonymous Inner Class Handlers in
JavaFX
In JavaFX, event handling can be done using inner classes and anonymous inner classes.
These approaches are useful when defining event handlers without needing separate
classes.

1. Inner Classes in Java

An inner class is a class defined within another class. In JavaFX, inner classes can be used
to handle events.

2. Anonymous Inner Class Event Handler

An anonymous inner class is a class without a name that is defined and instantiated at the
same time. It is useful for one-time event handling.

3. Comparison of Inner Class vs. Anonymous Inner Class vs. Lambda


Code Complexity
Approach Reusability Best Use Case
When the same handler
is used for multiple
Inner Class Medium High components.

When the handler is only


Anonymous Inner Class Low Low used once.

When the handler has a


Lambda Expression Lowest Medium simple action.

4. Best Practice: Use Lambda Expressions

Instead of inner classes, lambda expressions provide a cleaner and more readable
alternative.

Example: Using a Lambda Expression (Best Practice)

btn.setOnAction(event -> System.out.println("Button Clicked! (Lambda)"));

5. Summary

 Inner Classes: Best for reusable handlers across multiple components.


 Anonymous Inner Classes: Best for one-time event handling.
 Lambda Expressions: Best for simple, concise event handling (preferred in
JavaFX).

21
4.9 Handling Mouse and Key Events in JavaFX
JavaFX allows handling mouse and key events using inner classes, anonymous inner classes,
and lambda expressions.

1. Handling Mouse Events in JavaFX

Mouse events occur when the user clicks, moves, or hovers over a node.

2. Handling Key Events in JavaFX

Key events occur when the user presses, releases, or types a key.

3. Using Anonymous Inner Class for Event Handling

If we don’t want to use lambdas, we can use


anonymous inner classes.

4. Using an Inner Class for Event Handling

We can also define a separate inner class for handling key events.

5. Summary of Approaches
Approach Best For Example
Lambda Expression btn.setOnAction(event ->
s Simple System.out.println("Clicked!")
handlers );
Anonymou s Inner Medium scene.setOnKeyPressed(new
Classes complexit y EventHandler<KeyEvent>()
{...});
Inner Classes Reusable scene.setOnKeyPressed(new KeyPressHandler());
handlers

22
4.10 Listeners for Observable Objects in JavaFX
In JavaFX, listeners allow us to track changes in observable objects (e.g.,
properties in UI components). This is useful for updating the UI dynamically when
values change.

1. What Are Observable Objects?

Observable objects notify listeners when their values change. JavaFX provides properties
like:

 StringProperty
 IntegerProperty
 DoubleProperty
 BooleanProperty
 ObjectProperty<T>

These properties support change listeners and invalid listeners.

2. Using a Change Listener

A change listener (ChangeListener<T>) is triggered when a property’s value changes.

3. Using a Listener on a UI Component

We can listen to changes in JavaFX components, such as a slider updating a label


dynamically.

4. Using an Invalidation Listener

An invalidation listener (InvalidationListener) is triggered when a property becomes invalid


(even if the value is the same).

5. Summary of Listeners
When It Trigger
s
Listener Type Example
When the
value changes property.addListener((o bs, old, new) -> {...});
ChangeListener
When the
property
InvalidationListen er become s property.addListener(ob s -> {...});
invalid

23
4.11 Animation in JavaFX
JavaFX provides a powerful animation framework that allows smooth transitions,
movements, and effects for UI elements. The JavaFX Animation API includes various
animation classes like TranslateTransition, FadeTransition, RotateTransition, and
Timeline.

1. Types of Animations in JavaFX

1. Transition-Based Animations
o TranslateTransition (Move)
o RotateTransition (Rotate)
o ScaleTransition (Resize)
o FadeTransition (Fade in/out)
o FillTransition (Change color)
o StrokeTransition (Change stroke color)
o SequentialTransition (Multiple animations in sequence)
o ParallelTransition (Multiple animations simultaneously)
2. Timeline Animation
o Used for custom animations by updting values over time.

2. Basic Move Animation Using TranslateTransition

TranslateTransition moves a node from one position to another.

3. Rotate Animation Using RotateTransition

RotateTransition rotates a node.

4. Fade Animation Using FadeTransition

FadeTransition gradually changes the opacity of a node.

5. Custom Animation Using Timeline

A Timeline updates values dynamically over time.

6. Combining Animations Using SequentialTransition and ParallelTransition

Sometimes, we need multiple animations one after another (SequentialTransition) or


simultaneously (ParallelTransition).

24
7. Summary of JavaFX Animations
Animation Type Purpose

TranslateTransition Moves a node along X/Y

RotateTransition Rotates a node

ScaleTransition Resizes a node

FadeTransition Changes opacity

Timeline Custom animations

SequentialTransition Plays animations in sequence

Plays animations at the same time


ParallelTransition

25
Unit – 5
JavaFx UI controls and multimedia

5.1 JavaFX UI Controls


Every user interface considers the following three main aspects −
1. UI elements − These are the core visual elements which the user eventually sees and
interacts with.
2. Layouts − They define how UI elements should be organized on the screen.
3. Behavior − These are events which occur when the user interacts with UI elements.

❖ JavaFX provides several classes in the package javafx.scene.control.

Figure: JavaFX UI Controls

26
S. No. UI Control Description Constructors
Component that is used to define a simple new Label()
1. Label text on the screen. It is an not editable new Label(String S, Node n)
text control. new Label(String s)
Used to get the input from the user in the
2. TextField form of text. Allows to enter a limited New TextField()
quantity of text.
Used to get the kind of information from
the user which contains various choices. new CheckBox()
3. CheckBox
User marked the checkbox new CheckBox(String s)
either on (true) or off(false).
Used to provide various options to the
user. The user can only choose one new RadioButton()
4. RadioButton
option among all. A radio button is new RadioButton(String s)
either selected or deselected.
Component that controls the function of new Button()
5. Button the application. new Button(String s)
new ComboBox
Shows a list of items out of which user
6. ComboBox new
can select at most one item ComboBox(ObservableList i)
Shows a set of items and allows the user
to select a single choice and it will show
new ChoiceBox
the currently selected item on the top.
7. ChoiceBox new
ChoiceBox by default has no
ChoiceBox(Observa
selected item unless otherwise
selected. bleList i)
Enables users to choose one or more
8. ListView options from a predefined list of choices. new ListView();

It provides a scrollable view of UI


Elements. It is a container that has two
scrollbars around the component it
contains if the component is larger than
9. ScrollPane new ScrollPane();
the visible area of the ScrollPane. The
scrollbars enable the user to scroll around
the component shown inside
the ScrollPane
10. Textarea The TextArea control is a graphical user
interface component that allow users to
enter and display multiple lines of plain TextArea()
text. It is mostly used to collect New TextArea(String str)
information like comments, feedbacks
and descriptions.
1.Button

A Button is a graphical element in a JavaFX application that can be clicked to trigger an


action. Buttons are widely used in GUI applications as the main interactive controls. The user
interacts with the button by clicking it.

 Methods:
o setText(String text): Sets the text displayed on the button.
o setOnAction(EventHandler<ActionEvent> event): Sets the action handler,
which triggers when the button is clicked.
o setDisable(boolean value): Disables the button, preventing the user from
interacting with it.
o setStyle(String style): Allows you to apply CSS styling to the button.
 Example:

Button button = new Button("Click Me!");


button.setOnAction(event -> {
System.out.println("Button clicked!");
});
button.setStyle("-fx-background-color: #4CAF50; -fx-text-fill: white;");

2. Checkbox

A CheckBox is a type of toggle button that allows the user to select or deselect an option,
typically for binary decisions like "yes/no" or "on/off". A checkbox can be selected or
unchecked by the user.

 Methods:
o setSelected(boolean value): Sets the checkbox to be selected or deselected
programmatically.
o isSelected(): Returns whether the checkbox is selected or not.
o setOnAction(EventHandler<ActionEvent> event): Sets an event handler when
the checkbox's state changes (checked/unchecked).
o setText(String text): Sets the label for the checkbox.
 Example:

CheckBox checkBox = new CheckBox("Accept Terms");


checkBox.setOnAction(event -> {
if (checkBox.isSelected()) {
System.out.println("Checkbox selected");
} else {
System.out.println("Checkbox deselected");
}
});

3. RadioButton

A RadioButton is part of a group where only one radio button can be selected at a time.
These are often used when you need the user to select one option from a predefined set
(e.g., "Yes" or "No").
 Methods:
o setSelected(boolean value): Sets the radio button to be selected or
deselected programmatically.
o isSelected(): Returns whether the radio button is selected.
o setToggleGroup(ToggleGroup group): Associates the radio button with a
ToggleGroup, which ensures that only one radio button is selected at a time
within the group.
o setText(String text): Sets the label for the radio button.

 Example:

ToggleGroup group = new ToggleGroup();


RadioButton radioButton1 = new RadioButton("Option 1");
radioButton1.setToggleGroup(group);
RadioButton radioButton2 = new RadioButton("Option 2");
radioButton2.setToggleGroup(group);

4. TextField

A TextField is a one-line input field that allows the user to enter text. It is typically used
when you need the user to provide a short input (e.g., a name, search term, etc.).

 Methods:
o setText(String text): Sets the text in the text field.
o getText(): Retrieves the current text in the text field.
o setPromptText(String prompt): Sets a placeholder text that is shown when the
field is empty.
o setOnAction(EventHandler<ActionEvent> event): Defines an action when the
user presses Enter within the text field.

 Example:

TextField textField = new TextField();


textField.setPromptText("Enter your name");
textField.setOnAction(event -> {
System.out.println("User input: " + textField.getText());
});

5. TextArea

A TextArea is similar to a TextField but is used for multi-line text input. It is useful for
taking longer inputs like paragraphs, comments, or addresses.

 Methods:
o setText(String text): Sets the text inside the text area.
o getText(): Retrieves the text inside the text area.
o setWrapText(boolean value): Enables or disables word wrapping within the
text area.
o setPromptText(String prompt): Sets placeholder text when the area is empty.
o setEditable(boolean value): Makes the text area editable or not.

 Example:

TextArea textArea = new TextArea();


textArea.setPromptText("Enter your message here");
textArea.setWrapText(true);
textArea.setEditable(true);

6. ComboBox

A ComboBox (or drop-down list) lets users choose an option from a predefined set of
items. It combines a button and a list into one control.

 Methods:
o setItems(ObservableList<T> items): Sets the items to be displayed in the
ComboBox.
o getValue(): Gets the currently selected value.
o setOnAction(EventHandler<ActionEvent> event): Handles actions when the
selection changes.
o setEditable(boolean value): Makes the ComboBox editable, allowing the user
to type custom values.
 Example:

ComboBox<String> comboBox = new ComboBox<>();


comboBox.getItems().addAll("Apple", "Banana", "Orange");
comboBox.setOnAction(event -> {
System.out.println("Selected: " + comboBox.getValue());
});

7. ListView

A ListView displays a list of items and allows the user to select one or more items. It is
especially useful for displaying and selecting items from a larger set.

 Methods:
o setItems(ObservableList<T> items): Sets the list of items.
o getSelectionModel().getSelectedItem(): Retrieves the selected item from the
ListView.
o setOnMouseClicked(EventHandler<MouseEvent> event): Defines an action
when an item is clicked.
o getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE): Allows
multiple items to be selected.
 Example:

ListView<String> listView = new ListView<>();


listView.getItems().addAll("Item 1", "Item 2", "Item 3");
listView.setOnMouseClicked(event -> {
System.out.println("Selected: " + listView.getSelectionModel().getSelectedItem());
});

8. Scrollbar

A Scrollbar allows users to scroll through content when it overflows the visible area, either
horizontally or vertically.

 Methods:
o setMin(double value): Sets the minimum value (scroll position).
o setMax(double value): Sets the maximum value.
o setValue(double value): Sets the current value (scroll position).
o valueProperty(): Used to track changes in the scroll position.
 Example:

ScrollBar scrollBar = new ScrollBar();


scrollBar.setMin(0);
scrollBar.setMax(100);
scrollBar.setValue(50);
scrollBar.valueProperty().addListener((obs, oldValue, newValue) -> {
System.out.println("Scrollbar value: " + newValue);
});

9. Slider

A Slider is a control that allows the user to select a value from a range. It can be used for
things like volume control, progress tracking, or setting a parameter within a defined range.

 Methods:
o setMin(double value): Sets the minimum value of the slider.
o setMax(double value): Sets the maximum value of the slider.
o setValue(double value): Sets the current value of the slider.
o valueProperty(): A property to bind or listen to the slider's value.
 Example:

Slider slider = new Slider();


slider.setMin(0);
slider.setMax(100);
slider.setValue(50);
slider.valueProperty().addListener((obs, oldValue, newValue) -> {
System.out.println("Slider value: " + newValue);
});

10. Video and Audio (MediaPlayer)

JavaFX allows for the inclusion of multimedia elements such as video and audio using
the Media and MediaPlayer classes. You can create a MediaPlayer to control the playback of
video and audio files.
Video:

A MediaPlayer can be used to control and display video content in a MediaView.

 Methods:
o Media(String url): Initializes a media file (video file).
o MediaPlayer(Media media): Initializes a media player for the media file.
o play(): Starts playing the video.
o pause(): Pauses the video.
 Example (Video):

java
Copy
Media media = new Media("file:///path/to/video.mp4");
MediaPlayer mediaPlayer = new MediaPlayer(media);
MediaView mediaView = new MediaView(mediaPlayer);
mediaPlayer.play();

Audio:

Similarly, the MediaPlayer can be used for audio files like MP3s or WAVs.

 Example (Audio):

Media media = new Media("file:///path/to/audio.mp3");


MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();

Example: (UI Controls)


package javafxapplication1;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class NewFXMain extends Application {

@Override
public void start(Stage primaryStage) {
// Create Labels
Label nameLabel = new Label("Name:");
Label emailLabel = new Label("Email:");
Label passwordLabel = new Label("Password:");
Label genderLabel = new Label("Gender:");
Label hobbiesLabel = new Label("Select Hobbies:");
Label listViewLabel = new Label("Available Hobbies:");

// Create TextFields
TextField nameField = new TextField();
nameField.setPromptText("Enter your name");

TextField emailField = new TextField();


emailField.setPromptText("Enter your email");

// Create PasswordField
PasswordField passwordField = new PasswordField();
passwordField.setPromptText("Enter your password");

// Create RadioButtons for gender


RadioButton maleRadio = new RadioButton("Male");
RadioButton femaleRadio = new RadioButton("Female");

// Group RadioButtons so only one can be selected


ToggleGroup genderGroup = new ToggleGroup();
maleRadio.setToggleGroup(genderGroup);
femaleRadio.setToggleGroup(genderGroup);

// Create CheckBoxes for hobbies


CheckBox readingCheckBox = new CheckBox("Reading");
CheckBox travelingCheckBox = new CheckBox("Traveling");
CheckBox cookingCheckBox = new CheckBox("Cooking");
CheckBox sportsCheckBox = new CheckBox("Sports");
CheckBox musicCheckBox = new CheckBox("Music");

// Create ListView for available hobbies


ListView<String> hobbiesListView = new ListView<>();
hobbiesListView.getItems().addAll("Reading", "Traveling", "Cooking", "Sports", "Music");
hobbiesListView.setPrefHeight(100);

// Create ComboBox (Dropdown) for country selection


ComboBox<String> countryComboBox = new ComboBox<>();
countryComboBox.getItems().addAll("USA", "India", "UK", "Canada", "Australia");

// Create Submit Button


Button submitButton = new Button("Submit");

// Layout using GridPane


GridPane grid = new GridPane();
grid.setVgap(10);
grid.setHgap(10);

// Add controls to the grid


grid.add(nameLabel, 0, 0);
grid.add(nameField, 1, 0);
grid.add(emailLabel, 0, 1);
grid.add(emailField, 1, 1);

grid.add(passwordLabel, 0, 2);
grid.add(passwordField, 1, 2);

grid.add(genderLabel, 0, 3);
grid.add(maleRadio, 1, 3);
grid.add(femaleRadio, 1, 4);

// Add hobbies checkboxes


grid.add(hobbiesLabel, 0, 6);
grid.add(readingCheckBox, 1, 6);
grid.add(travelingCheckBox, 1, 7);
grid.add(cookingCheckBox, 1, 8);
grid.add(sportsCheckBox, 1, 9);
grid.add(musicCheckBox, 1, 10);

// Add ListView for available hobbies


grid.add(listViewLabel, 0, 11);
grid.add(hobbiesListView, 1, 11);

// Add ComboBox for country


grid.add(new Label("Select Country:"), 0, 12);
grid.add(countryComboBox, 1, 12);

// Add Submit Button


grid.add(submitButton, 1, 13);

// Create Scene
Scene scene = new Scene(grid, 400, 500);

// Set Stage (window) properties


primaryStage.setTitle("Registration Form with ListView");
primaryStage.setScene(scene);

// Show the Stage


primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}

You might also like