JavaFx
JavaFx
JavaFX is a set of graphics and media packages that enables developers to create rich,
interactive user interfaces (UIs) for desktop, mobile, and embedded devices. I
1. FXML: A markup language similar to HTML that allows UI design separately from
application logic.
3. CSS Styling: JavaFX supports styling through CSS to make UIs visually appealing and easy
to modify.
4. Animations & Effects: It provides tools for creating smooth animations, transitions, and
visual effects.
6. WebView: A browser component that allows embedding web content inside JavaFX
applications.
JavaFX is widely used for building rich desktop applications due to its flexibility and ability to
create polished, interactive UIs with Java.
Layouts
In JavaFX, layouts (also called layout panes) are containers that manage the arrangement of
their child nodes (e.g., buttons, labels, text fields) in a specific way. Layout panes handle the
positioning and sizing of their children automatically, which simplifies the design of user
interfaces. JavaFX provides various types of layout panes…..
Pane
In JavaFX, a Pane is a container that holds and organizes nodes (elements like shapes, text,
images, etc.) in a scene. It serves as a layout component that allows you to position child nodes
by specifying their exact x and y coordinates.
For example:
Pane pane = new Pane();
rect.setFill(Color.BLUE);
pane.getChildren().addAll(rect, text);
primaryStage.setScene(scene);
primaryStage.show();
Note that: The coordinates of the upper left corner of the pane is (0,0) in the Java coordinate
system, as opposed to the conventional coordinate system where (0, 0) is at the center of the
window.
StackPane
In JavaFX, the StackPane is a layout container that arranges its child
nodes in a stack, where each new node is placed on top of the previous
one.
Key Characteristics:
1. Stacking Order: Each child node is placed on top of the previous
one. The order of nodes within the StackPane is based on the
order in which they are added. You can manipulate the stack by
changing the order of visibility or bringing specific nodes to the
front or back.
2. Alignment: You can align nodes within the StackPane using the
setAlignment method, allowing you to control the position of
each node (e.g., top-left, center, bottom-right, etc.)
Example Usage:
In a typical use case, you might add a Label, a Button, and a CheckBox
to a StackPane. You can toggle their visibility to manage which one is on
top, or use the toBack() and toFront() methods to change the stacking
order dynamically
VBox/HBox
In JavaFX, VBox is a layout container that arranges its children in a single vertical column. It’s
useful when you need to create a simple UI where components stack vertically. Each
component (like buttons, text fields, or labels) is placed one below the other, with optional
spacing and padding.
vbox.setPadding(new javafx.geometry.Insets(15));
primaryStage.setScene(scene);
primaryStage.setTitle("VBox Example");
primaryStage.show();
Key Properties
1. Spacing: Controls the space between each child in the VBox.
BorderPane
BorderPane is a layout manager in JavaFX that allows you to arrange nodes (UI components) in
five distinct regions: top, bottom, left, right, and center. This makes it especially useful for
creating UIs that have a fixed structure, like applications with a header, footer, sidebar, and
main content area. Each of these regions can contain only one node, but that node can itself
be a layout pane with other nested nodes.
//Example of BorderPane
1. Top: The status label (statusLabel) is placed at the top to show the game status.
2. Center: The Tic-Tac-Toe grid (GridPane with cells) is placed at the center.
3. Bottom: The restart button (VBox containing the button) is placed at the bottom.
• Bottom (setBottom(Node node)): Puts a node at the bottom (often used for footers).
• Left (setLeft(Node node)): Puts a node on the left side (often for sidebars).
• Right (setRight(Node node)): Puts a node on the right side (another option for
sidebars).
• Center (setCenter(Node node)): Puts a node in the center (usually the main content
area).
GridPane
GridPane is a JavaFX layout pane that arranges its children in a grid of rows and columns,
making it ideal for creating interfaces with a structured layout, like forms, tables, or, as in your
Tic-Tac-Toe game, a 3x3 game board. Each cell in a GridPane can contain one node, such as a
Label, Button, or any other JavaFX component.
1. Grid Configuration: A 3x3 grid of cells is defined, each cell containing a Label to
represent a space on the board.
2. Positioning Cells: Each Label cell is added to a specific row and column in the GridPane
to arrange the board layout.
• Row and Column Indexing: Rows and columns are indexed starting from zero. You
specify each child node’s location with a row and column index using add(Node child, int
columnIndex, int rowIndex).
• Alignment and Spacing: GridPane supports configuring alignment, horizontal (hgap) and
vertical (vgap) spacing between cells.
• Span: You can make nodes span multiple rows or columns, if needed, by specifying the
span using add(Node child, int columnIndex, int rowIndex, int colspan, int rowspan).
In your code:
• grid.setAlignment(Pos.CENTER); centers the grid in the parent container.
• The loop grid.add(cell, col, row); places each Label in its designated row and column,
creating the 3x3 structure needed for the Tic-Tac-Toe board.
UI Controls
In JavaFX, UI controls are essential components that allow you to create interactive user
interfaces for your applications. These controls help users interact with your application by
providing buttons, text input fields, selection options, and more.
1. Button: A clickable control that performs an action when pressed. It is often used in
forms, dialogs, or to trigger specific behavior in the app.
2. TextField: An input control that allows the user to enter a single line of text. It's
commonly used for text-based data entry such as username or password fields.
3. Label: A simple text element used to display information to the user. It is generally used
to describe other controls (e.g., "Enter your name").
5. RadioButton: Similar to a CheckBox but used in groups where only one option can be
selected at a time. Ideal for selecting from a list of mutually exclusive options.
6. ComboBox: A drop-down list that allows users to choose from a set of options. It
combines the functionality of a text field and a list view.
ComboBox<String> comboBox = new ComboBox<>();
7. Slider: A control that allows users to select a value from a continuous range by dragging
a slider handle. It’s great for adjusting values like volume or brightness.
8. ProgressBar: A visual indicator of progress for an ongoing task. It can display the current
state of a task, such as downloading or processing data.
9. TextArea: Similar to TextField but allows multiple lines of text input. It's ideal for longer
text entries like comments or descriptions.
10. MenuBar: A horizontal menu for adding dropdown menus to your app, typically used for
navigation or to group related actions (e.g., File, Edit).
Label
In JavaFX, a Label is a UI control that displays a small amount of text or an image to the user. It’s
primarily used to display non-interactive information, like titles, status messages, or, as in your
Tic-Tac-Toe game, X and O symbols in each cell of the board.
1. Text Display: Labels are commonly used to show text. You can set the text of a label
with setText(String text).
2. Styling: Labels support various styling options, allowing you to control the font size,
color, background color, borders, and more.
3. Non-Editable: Labels are read-only, meaning users can see the content but cannot
modify it directly.
4. Graphic Support: A label can also display an image or other JavaFX Node as a graphic
beside or instead of text.
• The Label is styled to appear like a game cell using properties like -fx-font-size, -fx-
background-color, and -fx-border-color.
• When a cell is clicked, the Label text is updated with "X" or "O" depending on the
player’s turn, giving the appearance of filling a Tic-Tac-Toe square.
• It uses inline CSS to set the font size to 20px and the text color to a shade of gray
(#333333).
The Label is an essential control for displaying text information to users and is flexible enough
for both static information and dynamically updated content, as in your game board.
Property binding
In JavaFX, property binding is a powerful feature that allows the value of one property to be
automatically updated based on changes to another property. This helps to maintain
synchronization between different UI elements or between the UI and the underlying data
model without needing to manually update values.
2. Binding: Binding links two properties so that when one property changes, the other is
updated automatically. JavaFX supports several types of bindings:
o Bidirectional binding: Both properties update each other.
o Unidirectional binding: One property updates another but not the reverse.
label.textProperty().bind(textField.textProperty());
In this case, whenever the text in the TextField changes, the Label's text updates automatically.
4. Advanced Binding: JavaFX also allows more complex bindings, such as using
ObjectBinding or StringBinding to perform transformations between properties:
Note: A target binds with a source using the bind method as follows: target.bind(source)
JavaFX style properties are similar to cascading style sheets (CSS) used to specify the styles for
HTML elements in a Web page. So, the style properties in JavaFX are called JavaFX CSS. In
JavaFX, a style property is defined with a prefix –fx-. Each node has its own style properties.
The syntax for setting a style is styleName:value. Multiple style properties for a node can be set
together separated by semicolon (;).
For example,
Event handler
An event handler is a block of code or a method that gets executed in response to an event. In
Java and many other programming languages, an event handler listens for specific events, such
as user interactions (e.g., button clicks, key presses) or system events (e.g., a timer reaching a
certain time). When an event occurs, the handler code is executed to perform actions, like
updating a display or processing user input.
1. Event: An event is an occurrence that a program can detect, such as clicking a button,
typing on the keyboard, or selecting a menu item.
2. Listener: A listener is an object that "listens" for a specific event. Once the event occurs,
it notifies the associated event handler.
3. Event Handler: The handler is the code that executes when the event occurs.
In this example:
• The event handler prints "Button was clicked!" to the console when the button is
clicked.
Types of Events and Their Handlers
Each type of event has a corresponding handler method, and you can define multiple handlers
to respond to various user interactions.Event handlers make applications interactive by
allowing the program to respond dynamically to user inputs and system signals.
OnAction method
In JavaFX, the OnAction method is commonly used with controls like Button, MenuItem, and
TextField. You can define an onAction event handler to specify what happens when the user
interacts with these controls (e.g., clicks a button).
@Override
System.out.println("Button clicked!");
}
ObservableList<Double>
The ObservableList<Double> in JavaFX is a specialized list that automatically notifies listeners
of any changes made to the list. It's part of the JavaFX collections framework and is widely
used in JavaFX applications for binding UI components to dynamic data.
1. Dynamic Updates: Any changes to the list (e.g., adding, removing, or updating points)
are automatically reflected in the associated Polyline shape in real time.
2. Listeners: You can attach listeners to monitor changes in the list (e.g., points being
added or removed).
Example of ObservableList<Double>
Polyline polyline = new Polyline();
// Adding points
// Modifying points
// Removing points
Real-Time Updates
Changes to the points list dynamically update the Polyline in the UI without requiring additional
code.
Image and ImageView
In JavaFX, Image and ImageView are key classes for working with images in your applications.
Here's a breakdown of each:
1. Image
• To load an image, you provide the URL or file path to the Image constructor.
The Image constructor also has optional parameters to control aspects like image width, height,
and whether the image should be loaded eagerly or lazily.
2. ImageView
• The ImageView class is a Node used to display an image on the scene. You set an Image
object to an ImageView to display the image.
• ImageView allows you to apply transformations like scaling, rotation, and mirroring to
the image.
CSS
In JavaFX, CSS is a powerful way to style your application's user interface. JavaFX supports a
subset of CSS that is similar to web CSS, but with a few differences specific to the JavaFX
platform.
• Inline CSS: Directly set style on JavaFX components using the setStyle() method.
• External CSS File: Link an external .css file to your JavaFX scene.
Create a .css file (e.g., styles.css) and place it in your resources or project directory. Then, you
can load it and apply it to the scene.
Example: styles.css
Css:
.button {
-fx-background-color: #FF6347;
-fx-text-fill: white;
-fx-font-size: 16px;
scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
JavaFX has some CSS properties that aren’t in standard web CSS. Here are a few common ones:
Shapes:
Polygon
In JavaFX, the Polygon class is used to create and display polygons. A polygon is a shape with
multiple straight lines connecting a series of points, where the first and last points are
connected. In JavaFX, you can create a polygon by specifying a list of points that define its
vertices.
polygon.getPoints().addAll(
);
polygon.setFill(Color.LIGHTBLUE);
polygon.setStroke(Color.DARKBLUE);
1. Creating a Polygon:
o We create a Polygon object and use the getPoints().addAll() method to add x and
y coordinates of the vertices.
2. Setting Appearance:
3. Adding to Pane:
o The polygon is added to a Pane, which is used as the root node of the scene.
Polyline
In JavaFX, a Polyline is a shape that represents a series of connected line segments. It is similar
to a Polygon, but the last point in a Polyline is not automatically connected back to the first
point, making it an open shape.You define a polyline by specifying a list of points (x, y
coordinates) that determine the vertices of the connected segments.
Circle
In JavaFX, the Circle class is used to create and display circles. A Circle object requires the
center coordinates (x and y) and a radius.
pane.getChildren().add(circle);
Explanation
1. Creating a Circle:
o Circle circle = new Circle(200, 200, 50); creates a circle with its center at
coordinates (200, 200) and a radius of 50.
2. Setting Appearance:
3. Adding to Pane:
o The circle is added to a Pane, which is used as the root node of the scene.
Note that the measurement units for graphics in Java are all in pixels.