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

JavaFx

JavaFX is a framework for creating rich user interfaces across various devices, featuring components like FXML for UI design, a scene graph for component relationships, and CSS for styling. It includes various layout panes such as Pane, StackPane, VBox, HBox, BorderPane, and GridPane to manage UI component arrangements. Additionally, JavaFX provides UI controls like buttons, text fields, and labels, along with features like property binding and event handling to enhance interactivity and responsiveness in applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JavaFx

JavaFX is a framework for creating rich user interfaces across various devices, featuring components like FXML for UI design, a scene graph for component relationships, and CSS for styling. It includes various layout panes such as Pane, StackPane, VBox, HBox, BorderPane, and GridPane to manage UI component arrangements. Additionally, JavaFX provides UI controls like buttons, text fields, and labels, along with features like property binding and event handling to enhance interactivity and responsiveness in applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

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.

2. Scene Graph: A tree-like structure that represents UI components and their


relationships.

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.

5. Media Support: JavaFX supports audio, video, and image rendering.

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.

Here are some key points about Pane:

1. Direct Children Positioning: Unlike other layout containers that automatically


arrange nodes (like VBox or HBox), a Pane simply displays its children at the positions
you specify. This gives you complete control over the layout.
2. Commonly Used for Custom Layouts: Pane is often used when you need custom
or precise layouts where you place each element individually.

3. Adding Nodes: You can add elements to a Pane by calling getChildren().add(node) or


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

For example:
Pane pane = new Pane();

// Add a rectangle and text to the pane

Rectangle rect = new Rectangle(50, 50, 100, 100);

rect.setFill(Color.BLUE);

Text text = new Text(70, 100, "Hello JavaFX");

pane.getChildren().addAll(rect, text);

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

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.

// Create buttons to add to the VBox

Button button1 = new Button("Button 1");

Button button2 = new Button("Button 2");

Button button3 = new Button("Button 3");

// Create a VBox layout and set spacing between nodes

VBox vbox = new VBox(10); // 10px spacing

vbox.getChildren().addAll(button1, button2, button3);

// Optional: set padding for VBox

vbox.setPadding(new javafx.geometry.Insets(15));

// Create the scene and add the VBox

Scene scene = new Scene(vbox, 200, 150);

primaryStage.setScene(scene);
primaryStage.setTitle("VBox Example");

primaryStage.show();

Key Properties
1. Spacing: Controls the space between each child in the VBox.

VBox vbox = new VBox(20); // 20 pixels between nodes

2. Padding: Adds space around the edges of the VBox.

vbox.setPadding(new Insets(10)); // Insets with 10px padding on all sides

3. Alignment: Aligns children within the VBox.

4. vbox.setAlignment(Pos.CENTER); // Aligns children in the center

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.

Key Points of BorderPane


• Top (setTop(Node node)): Puts a node at the top (often used for headers).

• 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.

Example of GridPane Usage in Code

In your Tic-Tac-Toe game, GridPane is used to create the game board:

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.

Key Points of GridPane

• 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).

Example Layout in Tic-Tac-Toe

In your code:
• grid.setAlignment(Pos.CENTER); centers the grid in the parent container.

• grid.setStyle(...) applies padding, background color, and gap styling.

• 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.

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

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.

TextField textField = new TextField();

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").

Label label = new Label("Hello, JavaFX!");

4. CheckBox: A toggleable option that can either be checked or unchecked. It is useful


when presenting binary choices, such as accepting terms and conditions.

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

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.

RadioButton radioButton = new RadioButton("Option 1");

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.

Slider slider = new Slider();

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.

ProgressBar progressBar = new ProgressBar();

9. TextArea: Similar to TextField but allows multiple lines of text input. It's ideal for longer
text entries like comments or descriptions.

TextArea textArea = new TextArea();

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).

MenuBar menuBar = new MenuBar();

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.

Key Features of a Label

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.

Example Usage in Your Tic-Tac-Toe Game

• Each cell on the Tic-Tac-Toe board is a Label.

• 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.

Example of Creating a Label in code:

Label label = new Label("Hello, World!");

label.setStyle("-fx-font-size: 20px; -fx-text-fill: #333333;");

In the above code:

• The Label displays "Hello, World!".

• 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.

Key Concepts of Property Binding:

1. Properties: JavaFX provides several types of properties, such as StringProperty,


IntegerProperty, BooleanProperty, etc. These are special wrappers around regular
values that provide built-in change listeners.

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.

3. Binding Example: For instance, binding the text of a Label to a TextField:

TextField textField = new TextField();

Label label = new Label();

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:

IntegerProperty value1 = new SimpleIntegerProperty(10);

IntegerProperty value2 = new SimpleIntegerProperty();

value2.bind(value1.add(5)); // value2 will always be value1 + 5

Note: A target binds with a source using the bind method as follows: target.bind(source)

Properties and Methods for Nodes


The abstract Node class defines many properties and methods that are common to all nodes.
Nodes share many common properties.

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,

the following statement circle.setStyle("-fx-stroke: black; -fx-fill: red;");


sets two JavaFX CSS properties for a circle.

This statement is equivalent to the following two statements. circle.setStroke(Color.BLACK);


circle.setFill(Color.RED); If an incorrect JavaFX CSS is used, your program will still compile and
run, but the style is ignored. Therotate property enables you to specify an angle in degrees for
rotating the node from its center. If the degree is positive, the rotation is performed clockwise;
otherwise, it is performed counterclockwise. For example, the following code rotates a button
80 degrees. button.setRotate(80); Listing 14.7 gives an example that creates a button, sets its
style, and adds it to a pane. It then rotates the pane 45 degrees and set its style with border
color red and background color light gray, as shown in Figure 14.8

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.

How Event Handlers Work

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.

// Setting an event handler for the button's onAction event

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

In this example:

• The button’s setOnAction method is used to set an event handler.

• The event handler prints "Button was clicked!" to the console when the button is
clicked.
Types of Events and Their Handlers

• ActionEvent: For actions like button clicks (setOnAction).

• KeyEvent: For keyboard input (setOnKeyPressed, setOnKeyReleased).

• MouseEvent: For mouse actions like clicking and moving (setOnMouseClicked,


setOnMouseMoved).

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).

Example with JavaFX Button

1. Using setOnAction in Code:

Button button = new Button("Click me");

// Set OnAction using a lambda


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

// Alternatively, use an EventHandler


button.setOnAction(new EventHandler<ActionEvent>()

@Override

public void handle(ActionEvent e) {

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.

In the context of the Polyline, the getPoints() method returns an ObservableList<Double>


where each pair of doubles in the list represents the x and y coordinates of a point.

Key Characteristics of ObservableList<Double>

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();

ObservableList<Double> points = polyline.getPoints(); // Access the points list

// Adding points

points.addAll(50.0, 50.0, 100.0, 100.0, 150.0, 50.0);

// Modifying points

points.set(0, 60.0); // Change the first x-coordinate to 60

// Removing points

points.remove(4, 6); // Remove the last point (150.0, 50.0)

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

• The Image class in JavaFX represents the actual image data.

• To load an image, you provide the URL or file path to the Image constructor.

// Load an image from a file path

Image image = new Image("file:path/to/your/image.png");

// Load an image from a URL

Image imageFromURL = new Image("https://example.com/image.png");

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.

// Create an ImageView and set an image

ImageView imageView = new ImageView(image);

// Set properties on the ImageView

imageView.setFitWidth(200); // Scale width to 200 pixels


imageView.setFitHeight(150); // Scale height to 150 pixels

imageView.setPreserveRatio(true); // Keep the original aspect ratio

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.

1. Applying CSS Styles to JavaFX

You can apply CSS to JavaFX in two main ways:

• Inline CSS: Directly set style on JavaFX components using the setStyle() method.

• External CSS File: Link an external .css file to your JavaFX scene.

Example of Inline CSS

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

button.setStyle("-fx-background-color: #FF6347; -fx-text-fill: white;");

Applying External CSS

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;

Applying the Stylesheet in JavaFX


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

StackPane root = new StackPane(button);

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

scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());

2. JavaFX-Specific CSS Properties

JavaFX has some CSS properties that aren’t in standard web CSS. Here are a few common ones:

• -fx-background-color: Background color of controls.

• -fx-text-fill: Text color for labels, buttons, etc.

• -fx-padding: Padding inside elements.

• -fx-border-color: Border color of controls.

• -fx-font-size: Font size for text.

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.

// Create a polygon with specified vertices

Polygon polygon = new Polygon();

polygon.getPoints().addAll(

100.0, 150.0, // Point 1 (x, y)

200.0, 50.0, // Point 2 (x, y)

300.0, 150.0, // Point 3 (x, y)


250.0, 250.0, // Point 4 (x, y)

150.0, 250.0 // Point 5 (x, y)

);

// Set polygon color and stroke

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.

o Each point is added as two consecutive numbers, representing the x and y


coordinates.

2. Setting Appearance:

o setFill(Color.LIGHTBLUE): Fills the polygon with a light blue color.

o setStroke(Color.DARKBLUE): Sets the outline of the polygon to dark blue.

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.

Key Features of Polyline:

1. Open Shape: Unlike a polygon, a polyline does not close itself.


2. Customizable: You can set properties like stroke color, width, and other styles.

3. Resizable: The points can be dynamically modified.

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.

// Create a pane to hold the circle

Pane pane = new Pane();

// Create a circle with a center at (200, 200) and radius 50

Circle circle = new Circle(200, 200, 50);

// Set circle color and stroke

circle.setFill(Color.LIGHTGREEN); // Fill color inside the circle

circle.setStroke(Color.DARKGREEN); // Border color of the circle

circle.setStrokeWidth(2); // Border width of the circle

// Add the circle to the pane

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:

o setFill(Color.LIGHTGREEN): Sets the fill color of the circle to light green.


o setStroke(Color.DARKGREEN): Sets the stroke (border) color of the circle to dark
green.

o setStrokeWidth(2): Sets the width of the stroke to 2 pixels.

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.

You might also like