Module 2
Java FX
JavaFX architecture, life cycle, collections, event, utilities,
scene, control, FXML and Webview.
What is JavaFX ?
★ JavaFX is a Java library used to create modern, rich, and
interactive graphical user interfaces (GUI) for desktop
applications.
★ JavaFX is the modern alternative to older Java GUI frameworks like
Swing and AWT.
What is JavaFX?
History of JavaFX
★ JavaFX was formerly developed by Chris Oliver. At that time, he was serving for
a company named See Beyond Technology Corporation.
★ Initially, the JavaFX project was recognized as Form Follows Functions (F3).
★ This project was designed with the aim of providing richer interfaces for
developing GUI applications.
★ Later in June 2005, Sun Micro-systems took the F3 project and changed its
name from F3 to JavaFX.
Timeline of JavaFX
● 2005 - Sun Microsystems took over the See Beyond company in June 2005 and acquired the
F3 project as JavaFX.
● 2007 - JavaFX was officially declared at Java One, a worldwide web conference that is held
yearly.
● 2008 - Net Beans integration with JavaFX was made open. The Java Standard Development
Kit for JavaFX 1.0 was also released in the same year.
● 2009 - The next version of JavaFX was released, i.e., JavaFX 1.2, and the support for JavaFX
Mobile was also introduced. In the same year only, Oracle Corporation also acquired Sun
Microsystems.
● 2010 - JavaFX version 1.3 was released in 2010.
● 2011 - In 2011, JavaFX version 2.0 came out.
● 2012 - The support for JavaFX Mac OS for desktop was introduced.
● 2014 - The most advanced version of JavaFX, i.e., JavaFX 8, was released as an indispensable
part of Java on the 18th of March 2014.
JavaFX architecture
1. JavaFX Architecture Layers
JavaFX has a layered architecture with the following key components:
a. JavaFX Application Layer
This is where developers write the main application logic, typically by extending the
javafx.application.Application class.
Responsibilities:
★ Launch and manage the lifecycle (init(), start(), stop())
★ Create and configure UI elements
★ Manage user interaction and events
B. Scene Graph Layer
A scene graph is a hierarchical tree of nodes representing the UI.
Key Classes:
★ Stage: Top-level container (like a window)
★ Scene: Holds the scene graph
★ Node: Base class for all visual elements (e.g., Button, Text, Pane)
C. Prism (Graphics Pipeline)
Prism is the rendering engine that converts the scene graph into visual output.
★ Uses hardware acceleration (via DirectX or OpenGL)
Falls back to software rendering if needed
D. Glass Windowing Toolkit
★ Glass is responsible for windowing, event handling, and interaction with native OS UI
systems.
★ Manages native windows, timers, input events (mouse, keyboard)
E. Quantum Toolkit
Quantum acts as a bridge between JavaFX (Application Layer) and Prism/Glass.
★ Manages threads (UI thread, render thread)
★ Ensures smooth rendering and user interaction
2. Threading in JavaFX
JavaFX has a single-threaded UI model:
★ All UI updates must be done on the JavaFX Application Thread
★ Background tasks should use Task, Service, or Platform.runLater()
3. Other Important Modules
➤ FXML
★ XML-based markup to define the UI layout declaratively.
★ Works with FXMLLoader.
➤ CSS Styling
★ JavaFX supports CSS to style components like in web development.
➤ Media and Web
★ javafx.media: Supports playing audio and video
★ javafx.web: Embedded WebView using WebKit engine
Features of JavaFX
Life cycle of JavaFX
In JavaFX, the application life cycle is managed by the Application class from
the javafx.application package. It defines how a JavaFX program starts, runs,
and ends.
Method Purpose Called By
init() Called before GUI is created. You Called once before start()
can initialize variables or read config
files here.
start(Stage Main method to build and show the Called on JavaFX Application
UI Thread
primaryStage)
stop() Called when the app is closed. Use it Called automatically on exit
to clean resources. start() is
abstract, so it must be overridden.
Life Cycle Flow
1. JVM calls: launch(args)
2. JavaFX runtime calls: init()
3. JavaFX runtime calls: start(Stage)
4. Application runs (user interacts with UI)
5. JavaFX runtime calls: stop() (when app closes)
Panes, UI Controls, and Shapes
Structure Layers
1. Stage:
★ It represents the main window (or a popup window).
★ Think of it as the outer frame where everything appears.
★ You set the title, size, and visibility.
2. Scene:
★ The Scene is the container for all content inside a stage.
★ You place layout containers (Parent) and UI elements inside the scene.
3. Parent (like Pane or Control):
★ A Parent is a node that can hold other nodes.
★ It's usually a layout manager (like VBox, HBox, etc.) or UI containers.
★ It defines how child nodes are arranged.
4. Nodes:
★ These are the individual UI components:
Buttons, TextFields, Shapes, Images, etc.
★ All visual elements in JavaFX are subclasses of Node.
JavaFX is a graphical user interface toolkit for building desktop and mobile applications. It is based
on the Java programming language and provides a rich set of features for creating user interfaces,
including:
❑ Stage: A Stage represents a top-level window on the screen. It contains a Scene, which is the
content of the window.
❑ Scene: A Scene is a container that holds the content of a window. It can contain any type of
JavaFX node, including controls, shapes, and text.
❑ Layout: A Layout is a way of arranging nodes in a Scene. There are many different types of layouts
available, such as BorderPane, FlowPane, and GridPane. The choice of layout depends on the specific
needs of the application.
❑ Control:A Control is a node that allows the user to interact with the application. Examples of
Controls include buttons, text fields, and check boxes.
❑ Event:An Event is a notification that is sent to a Control when a user interacts with it. For example,
a Button event is fired when the user clicks the button.
To create a JavaFX application, you must first create a Stage. You can then create a Scene and add it
to the Stage. Finally, you can add Controls to the Scene and arrange them using a Layout.
To listen for events, you can use the `onAction()` method. The `onAction()` method takes a lambda
expression as its argument. The lambda expression will be executed when the event occurs.
import javafx.application.Application;
public class MyFirstJavaFX extends Application
{
@Override
public void start(Stage primaryStage)
{
Button btOK = new Button("OK");
Scene scene = new Scene(btOK, 200, 250);
primaryStage.setTitle("MyJavaFX");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
What is a Stage in JavaFX?
★ A Stage in JavaFX is like a window in a desktop application.
★ It is where your user interface (UI) is displayed.
★ Think of it as the main container that holds everything (like buttons, text fields, etc.).
What is primaryStage?
★ When a JavaFX application starts, the system automatically creates a main window for you — this is
called the primaryStage.
★ It is the first and main stage (or window) of your application.
★ You use primaryStage to:
Set the window title
Attach a scene (UI content)
Show the window on the screen
JavaFX Utilities
In JavaFX, utilities refer to helper classes and tools that make it easier to
work with various aspects of JavaFX applications, such as layout, animations,
properties, bindings, controls, and event handling.
UI Controls Utilities Layout Utilities
JavaFX provides many built-in UI components in Helps in arranging controls:
javafx.scene.control package:
● HBox, VBox – horizontal/vertical layout
● Button, Label, TextField, TextArea,
PasswordField ● BorderPane – top, bottom, left, right, center
● ComboBox, ListView, TableView, TreeView ● GridPane – grid layout
● CheckBox, RadioButton, ToggleButton, Slider,
● StackPane, FlowPane, AnchorPane
ProgressBar
Animation and Timeline Utility Classes
For UI effects and transitions: ★ Platform.runLater(Runnable) – run
code on JavaFX Application Thread
★ Timeline – create time-based
animations
★ FXMLLoader – load .fxml UI layout
files
★ FadeTransition, TranslateTransition,
ScaleTransition, etc.
★ Alert, Dialog, FileChooser,
ColorPicker, Tooltip
★ PauseTransition – for delayed
execution
Debug and Styling Tools
★ Use -fx- CSS properties for styling (can apply in .css files)
★ Use SceneBuilder for designing JavaFX UIs visually
★ Scene.getStylesheets().add(...) – apply custom styles
Converters and Formatters
★ StringConverter – used in ComboBoxes, ListViews,
etc.
★ TextFormatter – restrict/format user input in
TextField
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.event.*;
import javafx.animation.*;
import javafx.beans.property.*;
// Multiple stages can be added beside the primaryStage
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
public class MultipleStageDemo extends Application
{
@Override // Override the start method in the Application class
public void start(Stage primaryStage)
{
// Create a scene and place a button in the scene
Scene scene = new Scene(new Button("OK"), 200, 250);
primaryStage.setTitle("MyJavaFX"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
Stage stage = new Stage(); // Create a new stage
stage.setTitle("Second Stage"); // Set the stage title
// Set a scene with a button in the stage
stage.setScene(new Scene(new Button("New Stage"), 100, 100));
stage.show(); // Display the stage
}
public static void main(String[] args)
{
launch(args);
}
}
HBox layout demo Code in javafx.
@Override
package practiceproject; public void start(Stage primaryStage) throws Exception
import java.io.*; {
import javafx.application.Application; Button bt1 = new Button("Click Me");
import javafx.scene.Scene; Button bt2 = new Button("Click Me");
Button bt3 = new Button("Click Me");
import javafx.scene.control.Button;
Button bt4 = new Button("Click Me");
import javafx.scene.layout.GridPane; Button bt5 = new Button("Click Me");
import javafx.scene.layout.HBox; HBox h = new HBox();
import javafx.stage.Stage; h.getChildren().add(bt1);
public class democlass extends Application{ h.getChildren().add(bt2);
h.getChildren().add(bt3);
public static void main(String[] args){ h.getChildren().add(bt4);
h.getChildren().add(bt5);
launch(); Scene sc = new Scene(h);
} primaryStage.setScene(sc);
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.show();
}
}
You need to create a horizontal row of buttons (Save, Cancel, Reset) that
resize proportionally when the window is resized.
Question:
Which layout will you use for this button group? How can you ensure that
each button expands equally with the window? Write a java code.
JavaFX UI Controls
JavaFX UI controls are the basic building blocks of graphical user
interfaces (GUIs) in JavaFX. They allow users to interact with
applications in a variety of ways, such as entering text, clicking buttons,
and selecting items from lists.
There are a wide variety of UI controls available in JavaFX, including:
❑ Buttons: Buttons allow users to trigger actions, such as opening a new window or submitting a
form.
❑ Text fields: Text fields allow users to enter text.
❑ Check boxes: Check boxes allow users to select or deselect items from a list.
❑ Radio buttons: Radio buttons allow users to select one item from a list.
❑ Choice boxes: Choice boxes allow users to select a single item from a list.
❑ List views: List views allow users to view and select items from a list.
❑ Table views: Table views allow users to view and edit data in a tabular format.
❑ Tree views: Tree views allow users to view and interact with hierarchical data.
❑ Progress bars:Progress bars allow users to track the progress of an operation.
package practiceproject;
import java.io.*;
import javafx.application.Application;
import javafx.scene.Scene;
@Override
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox; public void start(Stage primaryStage) throws
import javafx.scene.control.ComboBox; Exception {
import javafx.scene.control.Hyperlink; //creating textfield
import javafx.scene.control.Label; TextField t = new TextField();
import javafx.scene.control.ListView; VBox root = new VBox();
import javafx.scene.control.RadioButton;
//we need to add this button to this layout
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField; root.getChildren().add(t);
import javafx.scene.control.ToggleGroup; t.setMaxWidth(100);
import javafx.scene.image.Image; //we need to add this layout to a scene
import javafx.scene.image.ImageView; Scene sc = new Scene(root);
import javafx.scene.layout.HBox; primaryStage.setHeight(500);
import javafx.scene.layout.VBox;
primaryStage.setWidth(500);
import javafx.scene.paint.Color;
import javafx.scene.text.Font; primaryStage.setTitle("Controls Demo");
import javafx.stage.Stage; primaryStage.setScene(sc);
primaryStage.show();
public class democlass extends Application{
}
public static void main(String[] args){
}
launch(args);
}
Introduction to Event Handlers in JavaFX
Event handlers in JavaFX are used to listen for and handle events that occur in a scene. Events can be
generated by the user interacting with the UI, such as clicking a button or pressing a key, or by the system,
such as a window being resized or a file being dropped.
To handle an event, you must first register an event handler for the event. Event handlers can be
registered for individual nodes or for the entire scene. To register an event handler for a node, you use the
`addEventHandler()` method. To register an event handler for the scene, you use the `addEventFilter()`
method.
Event handlers are typically implemented as lambda expressions. Lambda expressions are a concise way to
write functions. For example, the following lambda expression registers an event handler for the `onClick()`
event of a button:
button.setOnAction(event -> {
// Handle the button click event
});
import javafx.application.Application;
import javafx.scene.Scene; This application will create a window with a button. When the
import javafx.scene.control.Button;
user clicks the button, nothing will happen, because we have not
import javafx.scene.layout.HBox;
added any event handlers.
import javafx.stage.Stage;
However, we can easily add an event handler to the button to
public class MyApp extends Application { handle the click event. Here is how to do that:
@Override
public void start(Stage stage) throws Exception { button.setOnAction(event -> {
Button button = new Button("Click Me!"); System.out.println("You clicked the button!");
});
HBox layout = new HBox(10);
layout.getChildren().add(button);
Scene scene = new Scene(layout);
Now, when the user clicks the button, the message
stage.setTitle("My JavaFX Application"); "You clicked the button!" will be printed to the
stage.setScene(scene); console.
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
@Override
Code for getting input from a text field in javafx public void start(Stage primaryStage) throws Exception {
import java.io.*;
//this is a demo for creating a textfield and password field in javafx
import javafx.application.Application; TextField name = new TextField();
import javafx.event.ActionEvent; name.setMaxWidth(300);
import javafx.event.EventHandler; PasswordField pass = new PasswordField();
import javafx.scene.Scene; pass.setMaxWidth(300);
import javafx.scene.control.Button; Button bt1 = new Button("Click here");
import javafx.scene.control.Label; Label lbl = new Label();
import javafx.scene.control.TextField; bt1.setOnAction(new EventHandler<ActionEvent>() {
import javafx.scene.layout.VBox; @Override
import javafx.scene.paint.Color; public void handle(ActionEvent event) {
lbl.setText("Welcome Mr. " +name.getText());
import javafx.scene.text.Font;
lbl.setTextFill(Color.RED);
import javafx.stage.Stage;
lbl.setFont(new Font(32));
}
public class democlass extends Application{ });
VBox root = new VBox();
public static void main(String[] args){ root.getChildren().addAll(name,pass,bt1,lbl);
//add this layout to a scene
launch(args); Scene sc = new Scene(root);
} //set scene with primary stage
primaryStage.setTitle("Javafx UI Control Demo");
primaryStage.setScene(sc);
primaryStage.setWidth(500);
primaryStage.setHeight(500);
primaryStage.show();
}
}
You have a TextField and a Label. When the user presses Enter after typing in the TextField, the label should
display the entered text.
Question:
How would you use an event handler to capture the Enter key and update the label?
Toggle Button Functionality:
You have a Button that should toggle its text between “Start” and “Stop” every time it is clicked.
Question:
Which event and logic would you use to achieve this behavior?
Background Color Change:
You want the background color of a Pane to change to a random color when a user double-clicks anywhere
inside it.
Question:
Which event type would you listen for, and how would you apply the color change?
Mouse Drag Rectangle Drawing:
Design a feature where the user can click and drag the mouse to draw a rectangle on a Pane.
Question:
Which sequence of mouse events would you use to implement this interaction?
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
public static void main(String[] args) {
import javafx.scene.control.TextField;
launch(args);
import javafx.scene.layout.VBox;
}
import javafx.stage.Stage;
}
public class TextFieldEnterExample extends Application {
@Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
Label label = new Label("Enter text and press Enter");
// Event handler for Enter key
textField.setOnAction(event -> {
String input = textField.getText();
label.setText(input);
});
VBox vbox = new VBox(10, textField, label);
Scene scene = new Scene(vbox, 300, 100);
primaryStage.setTitle("TextField Enter Example");
primaryStage.setScene(scene);
primaryStage.show();
}
Form Validation on Focus Change:
When the user leaves a TextField (focus lost), you want to validate that it's not empty. If it is, display a red
border around the field.
Question:
Which event handler would be appropriate, and how would you apply the style?
Detecting Resize Events:
When a window is resized, you want to adjust the layout of elements dynamically (e.g., center-align a Label).
Question:
How can you listen to and respond to window resize events in JavaFX?
Multi-Component Interaction
Linked ComboBox and ListView:
Selecting a category in a ComboBox updates a ListView to show relevant items.
Question:
Describe how event handlers can coordinate between these components to maintain consistency.
Event Propagation Control:
You have a VBox containing a Button. A mouse click on the VBox should log "VBox clicked", and a click on the
Button should log "Button clicked". You want to prevent the VBox event when the Button is clicked.
Question:
How can you control event propagation in this case?
Would you like the Java code answers for any of these?
Introduction to Menu in JavaFX
A menu in JavaFX is a popup window that contains a list of items. Users can select an item from the menu to trigger an
action. Menus are typically used to provide users with access to a variety of commands or options.
There are two types of menus in JavaFX:
• Menubar:A menubar is a horizontal bar that is typically located at the top of the window. It contains a list of menus.
• Context menu: A context menu is a popup menu that appears when the user right-clicks on a node in the scene.
Menus can contain a variety of items, including:
• Menu items: Menu items are the basic building blocks of menus. They allow users to trigger actions.
• Submenus: Submenus are menus that are contained within other menus. They allow users to group related menu items
together.
• Separators: Separators are horizontal lines that can be used to separate menu items.
To create a menu in JavaFX, you need to create a Menu object. You can then add menu items to the menu using the
`getItems()` method. To add a submenu to a menu, you need to create a Menu object and add it to the menu using the
`getItems()` method.
import javafx.application.Application;
import javafx.scene.Scene; public static void main(String[] args) {
import javafx.scene.control.Menu; launch(args);
import javafx.scene.control.MenuItem; }
import javafx.stage.Stage; }
public class MyApp extends Application { This application will create a window with a menubar that contains a single menu, the
File menu. The File menu contains three menu items: Open, Save, and Exit.
@Override To handle menu item events, you can use the `setOnAction()` method. The
public void start(Stage stage) throws Exception { `setOnAction()` method takes a lambda expression as its argument. The lambda
Menu fileMenu = new Menu("File"); expression will be executed when the menu item is selected.
Here is an example of how to handle the click event for the Open menu item:
MenuItem openMenuItem = new MenuItem("Open");
MenuItem saveMenuItem = new MenuItem("Save");
MenuItem exitMenuItem = new MenuItem("Exit"); openMenuItem.setOnAction(event -> {
// Open a file
fileMenu.getItems().addAll(openMenuItem, saveMenuItem, exitMenuItem); });
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(fileMenu);
Scene scene = new Scene(menuBar);
stage.setTitle("My JavaFX Application");
stage.setScene(scene);
stage.show();
}
Collections in JavaFX:
ObservableList
Used for lists that need to notify listeners when items are added, removed, or updated.
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
ObservableList<String> items = FXCollections.observableArrayList();
items.add("Item 1");
items.add("Item 2");
ListView<String> listView = new ListView<>(items);
import javafx.collections.FXCollections;
★ This imports the FXCollections utility class from the JavaFX library.
★ FXCollections provides static methods to create observable collections like
ObservableList, ObservableMap, and ObservableSet.
import javafx.collections.ObservableList;
★ This imports the ObservableList interface.
★ An ObservableList is a special type of List that notifies listeners when items are
added, removed, or changed—important for dynamic UIs in JavaFX.
ObservableList<String> items = FXCollections.observableArrayList();
★ This creates an observable list of strings.
★ FXCollections.observableArrayList() returns a new empty list that supports
observation—JavaFX controls (like ListView) can monitor it for changes.
★ items will hold the data for our UI.
items.add("Item 1");
★ Adds the string "Item 1" to the items list.
★ If this list is already bound to a UI component (like ListView), it will
automatically update and display this new item.
items.add("Item 2");
★ Similarly, adds another string "Item 2" to the list.
★ Now the list contains: ["Item 1", "Item 2"].
ListView<String> listView = new ListView<>(items);
★ This creates a new ListView UI component and binds it to the items list.
★ The ListView will automatically display all items in the ObservableList.
★ Whenever the list changes (e.g., item added, removed), the ListView will
reflect those changes in real time, no extra code needed.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox; public static void main(String[] args)
import javafx.stage.Stage; {
launch(args);
public class ObservableListExample extends Application { }
}
@Override
public void start(Stage primaryStage) {
// Create an ObservableList
ObservableList<String> fruits = FXCollections.observableArrayList(
"Apple", "Banana", "Orange", "Grapes"
);
// Create a ListView and bind the ObservableList to it
ListView<String> listView = new ListView<>(fruits);
// Layout
VBox root = new VBox(listView);
Scene scene = new Scene(root, 300, 200);
// Stage setup
primaryStage.setTitle("ObservableList Example");
primaryStage.setScene(scene);
primaryStage.show(); }
You are developing a JavaFX app that shows a list of books in a ListView. When a new
book is added to the list using a button, the UI should update automatically.
Question:
How will you design the ListView to automatically reflect changes when a book is
added or removed?
You're displaying student records in a TableView. If a student's mark is updated in
the backend list, the change should immediately reflect in the TableView.
Question:
What steps should you take to ensure that the TableView auto-updates when the
underlying data changes?
Hint: Consider using ObservableList<Student> and JavaFX Properties in the Student
class.
What is ObservableMap?
ObservableMap<K, V> is a JavaFX interface that extends Map<K, V>. It notifies
listeners when the map is modified — for example, when a key-value pair is
added, removed, or updated.
This is useful when you want your UI to react to changes in a map, just like
how ObservableList works with lists.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.collections.MapChangeListener;
import javafx.stage.Stage;
public class ObservableMapExample extends Application {
@Override
public void start(Stage primaryStage) {
ObservableMap<String, String> map = FXCollections.observableHashMap();
map.addListener((MapChangeListener.Change<? extends String, ? extends String> change) -> {
if (change.wasAdded()) {
System.out.println("Added: " + change.getKey() + " = " + change.getValueAdded());
}
if (change.wasRemoved()) {
System.out.println("Removed: " + change.getKey() + " = " + change.getValueRemoved());
}
});
map.put("name", "Alice");
map.put("age", "25");
map.remove("name");
}
public static void main(String[] args) {
launch(args);
ObservableMap<String, String> map = FXCollections.observableHashMap();
★ Creates an ObservableMap with key type String and value type String.
★ observableHashMap() is a method that creates a regular hash map, but with observable features —
i.e., it can trigger events when it changes.
map.addListener((MapChangeListener.Change<? extends String, ? extends String> change) -> {
★ Adds a change listener to the map.
★ Every time the map is modified, the change object provides information about what was added or
removed.
if (change.wasAdded()) {
System.out.println("Added: " + change.getKey() + " = " + change.getValueAdded());
}
Checks if something was added to the map.
If so, it prints the key and the new value.
if (change.wasRemoved()) {
System.out.println("Removed: " + change.getKey() + " = " + change.getValueRemoved());
}
Checks if something was removed from the map.
If so, it prints the key and the old value that was removed.
map.put("name", "Alice");
Adds a new key-value pair: "name" = "Alice".
This triggers the wasAdded() block in the listener, and prints:
Added: name = Alice
map.put("age", "25");
Adds another entry: "age" = "25".
This also triggers the listener and prints:
Added: age = 25
map.remove("name");
Removes the "name" entry from the map.
This triggers the wasRemoved() part of the listener, printing:
Removed: name = Alice
public static void main(String[] args) {
launch(args);
}
Standard Java entry point.
launch(args) is a static method from the Application class that starts the
JavaFX application, which then calls the start() method.
ObservableSet
ObservableSet is an interface in the javafx.collections package that extends
the standard java.util.Set but adds observability — meaning you can listen for
changes such as additions or removals of elements.
In JavaFX, ObservableSet<E> is part of the javafx.collections package.
It is a special version of the regular Set<E> (like HashSet), but it notifies
listeners when the content changes — making it perfect for UI data binding
and live updates in GUI applications.
Use ObservableSet when:
★ to track changes in a set (add/remove).
★ to automatically update the UI when the set changes.
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;
public class ObservableSetExample {
public static void main(String[] args) {
// Create an ObservableSet
ObservableSet<String> mySet = FXCollections.observableSet();
// Add a listener to track changes
mySet.addListener((SetChangeListener.Change<? extends String> change) -> {
if (change.wasAdded()) {
System.out.println("Added: " + change.getElementAdded());
}
if (change.wasRemoved()) {
System.out.println("Removed: " + change.getElementRemoved());
}
});
// Modify the set
mySet.add("Apple");
mySet.add("Banana");
mySet.remove("Apple");
}}
1. You’re building a settings window for a JavaFX application. Each setting has a name (String) and
a value (Object), and all settings are stored in a Map. When a setting is changed by the user,
the change must be reflected both in the UI and in the internal data.
Question:
How would you implement the settings data structure so that changes to the map automatically
update the UI?
2. You're designing a theme engine where UI colors and fonts are stored as key-value pairs in a
map ("backgroundColor" → "#ffffff"). When a theme changes, the UI should update
automatically.
Question:
How can you use ObservableMap<String, String> to dynamically change UI properties when the
theme values change?
Follow-up: Which listener would you attach to observe changes?
FXML
FXML is an XML-based user interface markup language created by
Oracle Corporation for defining the user interface of a JavaFX
application.FXML presents an alternative to designing user
interfaces using procedural code, and allows for abstracting
program design from program logic.
FXML
FXML is an XML-based language used in JavaFX to design user interfaces separately from the
application logic.
XML stands for "FXML Markup Language".
It allows developers and designers to define the structure and layout of the UI using XML.
FXML files are typically associated with a Java controller class that handles the interaction and
logic.
Helps separate UI from logic, making development more modular and easier to maintain
(like HTML + JavaScript).
You can load FXML files in Java using FXMLLoader.
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<VBox>
<children>
<Label text="Hello world FXML"/>
</children>
</VBox>
This example defines a VBox containing a single Label as child element. The VBox component is a JavaFX layout
component. The Label just shows a text in the GUI.
The first line in the FXML document is the standard first line of XML documents.
The following two lines are import statements. In FXML you need to import the classes you want to use. Both JavaFX
classes and core Java classes used in FXML must be imported.
Example : FXML Code
<AnchorPane xmlns:fx="http://javafx.com/fxml" fx:controller="sample.Controller">
<children>
<Label layoutX="20.0" layoutY="20.0" text="Hello, FXML!" />
<Button layoutX="20.0" layoutY="60.0" text="Click Me"
onAction="#handleButtonClick"/>
</children>
</AnchorPane>
Controller.java
package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class Controller {
@FXML
private Label label;
@FXML
private void handleButtonClick(ActionEvent event) {
label.setText("Button Clicked!");
}
sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane xmlns:fx="http://javafx.com/fxml" fx:controller="sample.Controller">
<children>
<Label fx:id="label" layoutX="20.0" layoutY="20.0" text="Hello, FXML!" />
<Button layoutX="20.0" layoutY="60.0" text="Click Me"
onAction="#handleButtonClick"/>
</children>
</AnchorPane>
// Main.java
import javafx.application.Application;
import javafx.fxml.FXMLLoader; public static void main(String[] args) {
import javafx.scene.Parent; launch(args);
import javafx.scene.Scene;
}
import javafx.stage.Stage;
}
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));// loading the FXML file
primaryStage.setTitle("FXML Demo");
primaryStage.setScene(new Scene(root, 300, 200));
primaryStage.show();
}
Folder Structure:
project-root/
├── Main.java
├── sample/
│ ├── Controller.java
│ └── sample.fxml
WebView
The WebView class in JavaFX is a UI component that allows you to
display web pages inside a JavaFX application.
It acts like a mini-browser within your Java app and uses the WebKit
rendering engine under the hood.
Class Purpose
WebView A Node that displays Web content
WebEngine The underlying engine that loads and renders the web page
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.scene.web.WebEngine;
import javafx.stage.Stage;
public class WebViewExample extends Application {
@Override
public void start(Stage primaryStage) {
// Create WebView and WebEngine
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
// Load a webpage
webEngine.load("https://www.google.com");
// Set the scene
Scene scene = new Scene(webView, 800, 600);
primaryStage.setTitle("JavaFX WebView Example");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
@Override
import javafx.application.Application; public void stop() throws Exception {
import javafx.stage.Stage; System.out.println("stop() called: Cleanup before exit");
import javafx.scene.Scene; }
import javafx.scene.control.Label;
public static void main(String[] args) {
public class LifeCycleDemo extends Application { System.out.println("Launching JavaFX Application...");
launch(args);
@Override }
public void init() throws Exception }
{
System.out.println("init() called: Perform initialization here");
}
@Override
public void start(Stage primaryStage) {
System.out.println("start() called: Setup and show UI");
Label label = new Label("Hello, JavaFX!");
Scene scene = new Scene(label, 300, 200);
primaryStage.setTitle("JavaFX Life Cycle");
primaryStage.setScene(scene);
primaryStage.show();
}