JavaFX
JavaFX
1
UNIT 4
JavaFx Basics and Event-driven programming and
animations
• 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 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.
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.
6) It provides the support for integrating audio, videos, and web applications.
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.
(1) start(): This is the method in which we write the code for JavaFX application. The
construct for this method is
(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;
@Override
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
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 javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
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 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.
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.
launch(args);
7
}
That's it. Now run your application program and a Label component with some message will
be displayed as an output.
1. StackPane
Example:
StackPane stackPane = new StackPane();
stackPane.getChildren().add(new Button("Click Me"));
2. FlowPane
Example:
FlowPane flowPane = new FlowPane();
flowPane.getChildren().addAll(new Button("1"), new Button("2"), new Button("3"));
8
3. GridPane
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"));
Example:
VBox vbox = new VBox(10); // Spacing of 10
vbox.getChildren().addAll(new Button("A"), new Button("B");
Example:
HBox hbox = new HBox(10);
10
hbox.getChildren().addAll(new Button("X"), new Button("Y"));
7. AnchorPane
Example:
AnchorPane anchorPane = new AnchorPane();
Button btn = new Button("Anchored");
AnchorPane.setTopAnchor(btn, 10.0);
anchorPane.getChildren().add(btn);
1. UI Controls
11
Common UI Controls in JavaFX
Control Description
Label Displays text or images
2. Shapes in JavaFX
Shape Description
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.
JavaFX properties allow binding UI elements like sliders and progress bars.
13
4. When to Use Property Binding?
1. Color Class
14
1.3 Using Colors in UI Controls
You can apply colors to UI elements like labels, buttons, etc. using setStyle().
2. Font Class
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:
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;"))
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
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
An event in JavaFX is an action that occurs when the user interacts with a GUI component,
such as:
JavaFX follows the event-driven programming model, where event listeners handle event
sources.
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
System.out.println("Button clicked!");
});
Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
primaryStage.show();
}
public static void main(String[] args)
{
18
launch(args);
}
}
btn.setOnAction(new EventHandler<ActionEvent>()
@Override
public void handle(ActionEvent event)
{
System.out.println("Button Clicked!");
}
});
Triggered by buttons, menu items, and text fields (when pressing Enter).
19
3 Key Events (KeyEvent)
scene.setOnKeyPressed(event ->
System.out.println("KeyPressed:" + event.getCode()));
1 Event Bubbling
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:
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.
An inner class is a class defined within another class. In JavaFX, inner classes can be used
to handle events.
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.
Instead of inner classes, lambda expressions provide a cleaner and more readable
alternative.
5. Summary
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.
Mouse events occur when the user clicks, moves, or hovers over a node.
Key events occur when the user presses, releases, or types a key.
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.
Observable objects notify listeners when their values change. JavaFX provides properties
like:
StringProperty
IntegerProperty
DoubleProperty
BooleanProperty
ObjectProperty<T>
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. 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.
24
7. Summary of JavaFX Animations
Animation Type Purpose
25
Unit – 5
JavaFx UI controls and multimedia
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();
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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):
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;
@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");
// Create PasswordField
PasswordField passwordField = new PasswordField();
passwordField.setPromptText("Enter your password");
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);
// Create Scene
Scene scene = new Scene(grid, 400, 500);