Open In App

JavaFX Tutorial

Last Updated : 15 Oct, 2025
Comments
Improve
Suggest changes
19 Likes
Like
Report

JavaFX is a Java library and GUI toolkit for developing Rich Internet Applications (RIA), web applications and desktop applications. Its main advantage is cross-platform compatibility, running on Windows, Linux, iOS android, desktops, web, TVs and tablets.

  • Rich GUI: Supports advanced UI controls, charts, tables and 3D graphics.
  • FXML: XML-based markup for declarative UI design.
  • Scene Builder: Visual drag-and-drop UI design tool.
  • Platform-independent: Runs on Windows, macOS, Linux and mobile platforms.
  • CSS Styling: UI components can be styled using CSS.
  • Multimedia Support: Handles audio, video and animation.
  • Hardware-accelerated Graphics: Uses GPU for better performance.
  • Integration: Works with Java libraries, multithreading, generics and lambda expressions.

Architecture of JavaFX

JavaFX architecture is layered to support the development of rich, cross-platform GUI and web applications.

javafx_graphics_engine
Architecture of JavaFX
  • JavaFX API: Top layer providing classes and packages for animations, UI controls, CSS styling, scene graph, events, media and application lifecycle.
  • Scene Graph: Core of GUI; hierarchical tree of nodes (root, branch, leaf) representing visual components.
  • Quantum Toolkit: Connects Prism (graphics engine) and Glass (windowing toolkit) to the API.
  • Prism: Hardware-accelerated 2D/3D graphics engine; falls back to software rendering if GPU is unavailable.
  • Glass Windowing Toolkit: Platform-dependent layer managing windows, events and OS surfaces.
  • WebView: Embeds web content (HTML5, CSS, JavaScript) and allows Java-JavaScript interaction.
  • Media Engine: High-performance multimedia pipeline (GStreamer) for audio and video playback.

LifeCycle of a JavaFX Application

A JavaFX application goes through four main phases, managed by the javafx.application.Application class:

lifecycle_of_javafx_application_
  • init(): Runs first on a non-GUI thread; used for initialization (e.g., loading resources).
  • start(Stage primaryStage): Main entry point; create scenes, UI, event handlers and show the stage.
  • Running: Application event loop handles user interactions and animations.
  • stop(): Called on exit; used for cleanup and resource release.

JavaFX 2D Shapes

2D shapes are geometrical figures represented on the X-Y plane (e.g., line, circle, rectangle, ellipse). In JavaFX, these shapes are part of the javafx.scene.shape package, with the Shape class as their root.

Steps to create a 2D shape

  1. Instantiate the shape class (e.g., Line line = new Line();).
  2. Set properties like coordinates or dimensions using setters (e.g., line.setStartX(0); line.setEndX(100);).
  3. Add to Group and display (root.getChildren().add(line);).

Common 2D Shape Classes

  • Line: Connects two points (Line).
  • Rectangle: Four sides with right angles (Rectangle).
  • Ellipse: Curve with two focal points (Ellipse).
  • Circle: Special ellipse with coinciding foci (Circle).
  • Arc: Portion of a circle/ellipse (Arc).
  • Polygon: Shape formed by connecting line segments (Polygon).
  • CubicCurve: Degree 3 curve (CubicCurve).
  • QuadCurve: Degree 2 curve (QuadCurve).

JavaFX 3D Shapes

3D shapes are solid geometrical figures represented using X, Y, Z coordinates. Unlike 2D shapes, 3D shapes require a Z coordinate. JavaFX supports 3D shapes through the javafx.scene.shape package, with Shape3D as the base class.

Types of 3D Shapes

1. Predefined 3D Shapes: Built-in classes:

  • Sphere: Perfectly round object (Sphere).
  • Box: Rectangular prism with height, width, depth (Box).
  • Cylinder: Solid with circular bases (Cylinder).

2. User-defined 3D Shapes: Using TriangleMesh to define custom points, faces and textures.

Steps to create a 3D shape

1. Instantiate shape

class: Box box = new Box();

2. Set properties:

box.setHeight(100);
box.setWidth(60);
box.setDepth(80);

3. Set camera:

PerspectiveCamera cam = new PerspectiveCamera();
scene.setCamera(cam);

4. Add to scene graph and stage:

Group root = new Group();

root.getChildren().add(box);

Scene scene = new Scene(root,500,500);

primaryStage.setScene(scene);

primaryStage.show();

JavaFX Effects

Effects in JavaFX enhance the visual appearance of nodes. They belong to the javafx.scene.effect package, with Effect as the root class. Effects are applied to nodes using the setEffect() method.

Steps to apply an effect

  1. Create the node (e.g., ImageView).
  2. Instantiate the effect class (e.g., Glow glow = new Glow();).
  3. Set effect properties (e.g., glow.setLevel(0.9);).
  4. Apply to node (imgView.setEffect(glow);).

Common JavaFX Effects

  • Blend: Combines pixels of two inputs.
  • Glow: Brightens pixels for a glowing effect.
  • Bloom: Similar to Glow, highlights bright areas.
  • Shadow: Creates a blurred duplicate behind a node.
  • Reflection: Adds a reflection beneath the node.
  • ColorAdjust: Alters hue, brightness, saturation, contrast.
  • SepiaTone: Applies a reddish-brown filter.
  • Lighting: Simulates light sources (point, spot, distant).
  • InnerShadow: Creates a shadow inside node edges.

JavaFX Texts

Text in JavaFX is represented by the Text class (javafx.scene.text), which also extends the Shape class, allowing both text-specific and shape properties.

Steps to create text

  1. Instantiate the Text class -> Text txt = new Text();
  2. Set properties -> txt.setText("Hello"); txt.setX(50); txt.setY(50);
  3. Add to group -> root.getChildren().add(txt);

Key Properties

  • Font: setFont(Font value)
  • Line Spacing: setLineSpacing(double)
  • Text Content: setText(String)
  • Underline: setUnderline(boolean)
  • Coordinates: setX(double), setY(double)

JavaFX Animations

Animations in JavaFX simulate motion by applying sequential transformations to nodes. All animation classes extend javafx.animation.Animation and are in the javafx.animation package.

Steps to apply an animation

  1. Create the node -> e.g., Square sqr = new Square(100,100,100,100); sqr.setFill(Color.GREEN);
  2. Instantiate the animation -> e.g., RotateTransition rotate = new RotateTransition();
  3. Set animation properties -> duration, axis, cycle count, etc.
  4. Attach target node -> rotate.setNode(sqr);
  5. Play animation -> rotate.play();

Common Animation Classes

  • ScaleTransition: Animates scaling of a node.
  • TranslateTransition: Moves a node from one location to another.
  • RotateTransition: Rotates a node around a specified axis.
  • FadeTransition: Animates node opacity over time.
  • StrokeTransition: Animates node stroke color between two values.
  • FillTransition: Animates node fill color between two values.
  • PathTransition: Moves a node along a specified path.
  • ParallelTransition: Runs multiple animations on a node simultaneously.

JavaFX Transformations 

Transformations modify the appearance or position of nodes, such as translation, rotation, scaling and shearing. All transformation classes belong to javafx.scene.transform.

Common Transformation Classes

  • Rotate: Rotates a node by a specific angle (Rotate).
  • Translate: Moves a node in X/Y/Z directions (Translate).
  • Scale: Changes the size of a node (Scale).
  • Shear: Slants the node along X/Y axes (Shear).

JavaFX UI Controls 

JavaFX provides a rich set of UI controls (buttons, text fields, lists, tables, etc.) for building interactive applications. All controls are part of the javafx.scene.control package and extend the Control class.

Common JavaFX Controls:

  • Button: Clickable button for user actions.
  • Label: Displays text or images .
  • TextField: Single-line text input
  • TextArea: Multi-line text input.
  • CheckBox: Selectable box .
  • RadioButton: Selectable option within a group.
  • ComboBox: Drop-down list (ComboBox).
  • ListView: Displays a scrollable list of items (ListView).
  • TableView: Displays tabular data.
  • Slider: Selects a numeric value from a range (Slider).
  • ProgressBar / ProgressIndicator: Shows task progress.

JavaFX Charts  

Charts represent data visually and are part of javafx.scene.chart.

Types of Charts

chart

1. PieChart: Circular chart showing proportions.

2. XYChart: Plots data on X and Y axes.

  • CategoryAxis: Represents categories.
  • NumberAxis: Represents numeric ranges.

Common Chart Classes

  • BarChart: Rectangular bars for values.
  • LineChart: Data points connected by lines.
  • AreaChart: Plots areas between points and axis.

JavaFX Layouts 

Layouts in JavaFX are top-level container classes that manage the arrangement of UI elements (scene-graph nodes). They act as parent nodes for all other nodes. All layout classes belong to the javafx.scene.layout package, with Pane as the root class.

Steps to Create a Layout

1. Instantiate the layout:

HBox root = new HBox();

2. Set layout properties:

root.setSpacing(20);

3. Add nodes to the layout:

root.getChildren().addAll(node1, node2);

Common JavaFX Layouts

  • HBox: Arranges nodes horizontally. (javafx.scene.layout.HBox)
  • VBox: Arranges nodes vertically. (javafx.scene.layout.VBox)
  • BorderPane: Arranges nodes in top, bottom, left, right, center. (javafx.scene.layout.BorderPane)
  • GridPane: Arranges nodes in a grid of rows and columns (ideal for forms). (javafx.scene.layout.GridPane)
  • FlowPane: Arranges nodes in a flow, wrapping horizontally or vertically. (javafx.scene.layout.FlowPane)
  • StackPane: Arranges nodes on top of each other like a stack. (javafx.scene.layout.StackPane)

JavaFX Event Handling

JavaFX allows user interaction with applications through events, which are notifications that something has happened (e.g., mouse click, key press, scroll). Handling events efficiently is key for responsive applications.

Processing Events

  • Events inform the application about user actions.
  • All events are instances of javafx.event.Event or its subclasses.
  • Common event classes include MouseEvent, KeyEvent, ScrollEvent, DragEvent.
  • Users can also create custom events by extending Event.

Types of Events

  1. Foreground Events: Triggered by direct user interaction (clicks, key presses, selection, scrolling).
  2. Background Events: Triggered without user action (e.g., OS interrupts, operation completion).

Common Event Classes

  • KeyEvent: Represents keyboard actions (keyPressed, keyReleased, keyTyped).
  • MouseEvent: Represents mouse actions (clicked, pressed, released, moved, entered, exited).
  • WindowEvent: Associated with window actions (showing, shown, hiding, hidden).
  • DragEvent: Triggered during drag-and-drop actions (dragEntered, dragDropped, dragOver, dragExited).

Setting up JavaFX in IDE (Eclipse)

To develop JavaFX applications, you need to configure JavaFX in your IDE. Below are the steps for Eclipse IDE:

Step 1: Install e(fx)clipse Plugin

  • Go to Help -> Eclipse Marketplace.
  • Search for "fx" and install e(fx)clipse 3.6.0.
  • Accept terms and click Next to install.

Step 2: Create a JavaFX Project

  • Restart Eclipse.
  • Go to File -> New -> Others -> JavaFX -> JavaFX Project.
  • Enter project details, click Next -> Finish.

Note: Eclipse does not yet know where JavaFX is installed; this is just the plugin setup.

Step 3: Download JavaFX SDK

  1. Download JavaFX from the official site (LTS recommended).
  2. Extract it to a known directory (remember the path).

Step 4: Create User Library

  1. Go to Windows -> Preferences -> Java -> Build Path -> User Libraries.
  2. Click New, give it a name (e.g., JavaFX).
  3. Click Add External JARs, select all JARs from the JavaFX lib folder.
  4. Click Apply and Close.
to 

Step 5: Configure Build Path

  1. Right-click project -> Build Path -> Configure Build Path.
  2. Go to Libraries -> Add Library -> User Library -> Select JavaFX.
  3. Click Finish -> Apply and Close.

Step 6: Configure Run Configuration

  1. Go to Run -> Run Configurations -> Arguments.
  2. Add VM arguments:

--module-path "YOUR_PATH_TO_FX\lib" --add-modules javafx.controls,javafx.fxml

After this one can start off with JavaFX operations as a window will be popped up by now.

JavaFX v/s Java Swing

Both JavaFX and Swing are GUI toolkits in Java, but they differ in design approach, capabilities and modernization level.

AspectJava SwingJavaFX
IntroductionLegacy GUI framework introduced in 1997.Modern framework introduced in 2008 for rich desktop and web applications.
UI ComponentsLarge set of mature and pluggable UI components.Supports CSS styling, FXML and hardware-accelerated UI components.
Graphics & AnimationLimited graphics capabilities, no built-in animation.Includes built-in animation, 2D/3D graphics and visual effects.
ArchitecturePartial MVC pattern support.Strong and consistent MVC architecture.
Event & Device SupportLess consistent event handling, no touch gesture support.Uniform event model, supports modern touch and gesture devices.

Real-world Applications made using JavaFX

JavaFX is used in multiple domains such as healthcare, aviation, finance and research.

  • Curator OR Caliop: Used in hospitals to manage and record surgery data.
  • Navigator Lynden: Helps dispatch managers monitor flight operations.
  • Atlas Trader: Commodity trading platform for assets like gold and oil.
  • Template Editor IAV: Analyzes and configures vehicle fleet data.
  • FORUM (Carl Zeiss Meditec AG): Clinical data management system combining Swing and JavaFX.
  • NEOS (EBU): Manages TV and radio transmission operations.
  • Deep Space Trajectory Explorer (NASA): Designs and visualizes interplanetary trajectories.

History of JavaFX

  • Initially developed by Chris Oliver at See Beyond Technology Corporation as Form Follows Functions (F3).
  • 2005: Sun Microsystems acquired F3 and renamed it JavaFX.

Timeline:

  • 2005: Sun Microsystems acquires F3.
  • 2007: JavaFX was officially announced at the Java One conference.
  • 2008: NetBeans integration; JavaFX SDK 1.0 released.
  • 2009: JavaFX 1.2 released; support for JavaFX Mobile; Oracle acquires Sun Microsystems.
  • 2010: JavaFX 1.3 released.
  • 2011: JavaFX 2.0 released.
  • 2012: Support for Mac OS desktop introduced.

Article Tags :

Explore