Draw a shape with a different color (JavaFX)
JavaFX Basics and Layout
Professor Sylvia Yeung
Motivations JavaFX is a new framework for developing Java GUI programs. The JavaFX API is an excellent example of how the object-oriented principle is applied.
This chapter serves two purposes.
First, it presents the basics of JavaFX programming.
Second, it uses JavaFX to demonstrate OOP.
Specifically, this chapter introduces the framework of JavaFX and discusses JavaFX GUI components and their relationships.
2
JavaFX vs Swing and AWT Swing and AWT are replaced by the JavaFX platform for developing desktop application and rich Internet applications (RIA).
- When Java was introduced, the GUI classes were bundled in a library known as the Abstract Windows Toolkit (AWT). AWT is fine for developing simple graphical user interfaces, but not for developing comprehensive GUI projects. In addition, AWT is prone to platform-specific bugs. - The AWT user-interface components were replaced by a more robust, versatile, and flexible library known as Swing components. Swing components are painted directly on canvases using Java code. Swing components depend less on the target platform and use less of the native GUI resource. -With the release of Java 8, Swing is replaced by a completely new GUI platform known as JavaFX.
3
What is JavaFX?
JavaFX is a Java library used to build Rich Internet Applications.
JavaFX applications are platform independent and run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.
From Java8, the JDK (Java Development Kit) includes JavaFX library in it. Therefore, to run JavaFX applications, you simply need to install Java8 or later version in your system.
JavaFX will be removed from the Java JDK as of JDK 11, which is due in September 2018.
Since Java 11, the graphical user interface (GUI) library we use in our Java books—Java FX—is no longer distributed as part of the Java Development Kit.
Web Resource:
The Java FX SDK installation instructions are at https://openjfx.io/openjfx-docs/
JavaFX API Documentation
https://openjfx.io/
JavaFX Application Structure JavaFX application has three major components:
-Stage
- Scene
- Notes
Stage
• A stage (a window) contains all the objects of a JavaFX application.
• It is represented by Stage class of the package javafx.stage
• The primary stage is created by the platform itself.
• The created stage object is passed as an argument to the start() method of the Application class
• call the show() method to display the content of a stage
Scene
• A scene represents the physical contents of a JavaFX application.
•It contains all the contents of a scene graph.
•The class Scene of the package javafx.scene represents the scene object
•At an instance, the scene object is added to only one stage.
•You can opt for the size of the scene by passing its dimensions (height and width) along with the root node to its constructor.
Scene Graph and Nodes
A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast, a node is a visual/graphical object of a scene graph.
A node may include – 1. Geometrical (Graphical) objects (2D and 3D) – Circle, Rectangle, Polygon, etc.
2. UI Controls – Button, Checkbox, Choice Box, Text Area, etc.
3. Containers (Layout Panes) – Border Pane, Grid Pane, Flow Pane, etc.
4. Media elements – Audio, Video and Image Objects
In general, a collection of nodes makes a scene graph.
The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all the nodes.
Each node in the scene graph has a single parent, and the node which does not contain any parents is known as the root node.
In the same way, every node has one or more children, and the node without children is termed as leaf node; a node with children is termed as a branch node .
A node instance can be added to a scene graph only once. The nodes of a scene graph can have Effects, Opacity, Transforms, Event Handlers, Application Specific States.
Root node – The first Scene Graph is known as the Root node.
Branch Node/Parent Node – The node with child nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types-
Group – A group node is a collective node that contains a list of children nodes. Any transformation, effect state applied on the group will be applied to all the child nodes.
Region – It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control.
WebView – This node manages the web engine and displays its contents.
Leaf Node – The node without child nodes. For example, Rectangle, Ellipse, Box, ImageView, MediaView.
It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene.
Creating a JavaFX Application
To create a JavaFX application, you need to
- instantiate the Application class
- implement its abstract method start() – In this method, you will write the code for the JavaFX Application
Application Class
- of the package javafx.application
In the main method, you have to launch the application using the launch() method
Within the start() method, you need to follow the steps given below-
Prepare a scene graph with the required nodes
Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it.
Prepare a stage and add the scene to the Stage and display the contents of the stage.
Preparing the Scene Graph
As per your application, you need to prepare a scene graph with required nodes. Since the root node if the first node, you need to create a root node. As a root node, you can choose from the Group, Region or WebView.
Group class – which belongs to the package javafx.scene
Group root = new Group();
//Retrieving the observable list object
ObservableList list = root.getChildren();
//setting the text object as a node
List.add(NodeObject);
Group root = new Group(NodeObject);
//Add Node objects to the group, just by passing them to the Group class and to its constructor
Preparing the Scene:
A JavaFX scene is represented by the Scene class of the package javafx.scene.
Scene scene = new Scene (root);
//root is the object of scene graph
Or pass two parameters of double type representing the height and width of the scene:
Scene scene = new Scene(root, 600, 300);
Preparing the Stage: It is represented by the Stage class of the package javafx.stage. An object of this class is passed as a parameter of the start() method of the Application class.
Using this object, you can perform various operations on the stage. Primarily you can perform the following –
- Set the title for the stage using the method setTitle()
- Attach the scene object to the stage using the setScene() method
- Display the contents of the scene using the show() method
Basic Structure of a JavaFX Application
Application
Override the start(Stage) method
Stage, Scene, and Nodes
18
Stage
Scene
Button
You may think of stage as the platform to
support scenes, and nodes as actors to
perform in the scenes.
A Scene object can be created using the
constructor Scene(node, width, height).
A Stage object is a window. A Stage object called
primary stage is automatically created by the
JVM when the application is launched.
(a) Stage is a
window for displaying
a scene that contains
nodes.
By default, the user can resize the stage. To prevent the user from
resizing the stage, invoke stage.setResizable(false).
What is the output?
Multiple stages can be displayed in a JavaFX program.
Problem? The button is always centered in the scene and occupies the entire window no matter how you resize it.
You can fix the problem by setting the position and size properties of a button.
However, a better approach is to use container classes, called panes, for automatically laying out the nodes in a desired location and size.
You place nodes inside a pane then place the pane into a scene. A node is a visual component such as a shape, an image view, a UI control, a group, or
a pane.
A shape refers to a text, line, circle, ellipse, rectangle, arc, polygon, polyline, and so on.
A UI control refers to a label, button, check box, radio button, text field, text area, and so on.
A group is a container that groups a collection of nodes. You can apply transformations or effects to a group, which automatically apply to all the children in the group.
Panes, UI Controls, and Shapes
23
A button is placed in the center of the pane.
The getChildren() method returns an instance of
javafx.collections.ObservableList.
ObservableList behaves very much like an ArrayList for
storing a collection of elements. Invoking add(e) adds an element to the list.
getChildren().add() vs. getChildren().addAll() StackPane pane = new StackPane();
pane.getChildren().add(new Button("OK")); //add one note
pane.getChildren().addAll( new Rectangle(100,100,Color.BLUE), new Label("Go!")); //add multiple notes
Binding Properties
JavaFX introduces a new concept called binding property that enables a target object to be bound to a source object. If the value in the source object changes, the target property is also changed automatically. The target object is simply called a binding object or a binding property.
26
The target object is called a binding object or a binding property, and the
source object is called a bindable object or observable object.
UNI-BINDING: BIDIRECTIONAL BINDING: bindBidirectional()
bind()
To be bound bidirectionally using the
bindBidirectional method
A binding property is an object. JavaFX defines binding properties for primitive types and strings.
For a double/float/long/int/boolean value, its binding property type is DoubleProperty/FloatProperty/LongProperty/IntegerProperty/BooleanProperty respectively.
For a string, its binding property type is StringProperty. These properties are also subtypes of ObservableValue. Therefore, they can be used as both source and target in a binding.
The program creates an instance of DoubleProperty using - SimpleDoubleProperty(1) (line 6).
Note that DoubleProperty, FloatProperty, LongProperty, IntegerProperty, and BooleanProperty are abstract classes.
Their concrete subclasses SimpleDoubleProperty, SimpleFloatProperty, SimpleLongProperty, SimpleIntegerProperty, and SimpleBooleanProperty are used to create instances of these properties.
These classes are very much like wrapper classes Double, Float, Long, Integer, and Boolean with additional features for property binding.
What will be the output if line 8 is replaced by d1.bind(d2.add(3))?
The Color Class
30
The Font Class
31
Layout Panes JavaFX provides many types of panes for organizing nodes in a container.
33
Pane import javafx.scene.layout.Pane;
No relocate method
FlowPane
35
GridPane
37
Example
gripPane.add(new Label(“Amount”), 0, 0); //for Amount label object
add(Node, Column number, row number) method
add(Node, Column number, row number)
BorderPane
40
HBox
41
VBox
42
import javafx.scene.layout.VBox;
StackPane Public class StackPane extends Pane
- StackPane lays out its children in a back-to-front stack
-The stackpane will attempt to resize each child to fill its content area.
If the child could not be sized to fill the stackpane (either because it was not resizable or its max size prevented it) then it will be aligned within the area using the alignment property, which defaults to Pos.CENTER.
StackPane example: StackPane stack = new StackPane(); stack.getChildren().addAll(new Rectangle(100,100,Color.BLUE), new Label("Go!));
import javafx.scene.layout.StackPane;
TilePane
- TilePane lays out its children in a grid of uniformly sized "tiles".
- A horizontal tilepane (the default) will tile nodes in rows, wrapping at the tilepane's width.
- A vertical tilepane will tile nodes in columns, wrapping at the tilepane's height.
import javafx.scene.layout.TilePane;
TitledPane import javafx.scene.control.TitledPane;
- public class TitledPane extends Labeled - A TitledPane is a panel with a title that can be opened and closed. - The panel in a TitledPane can be any Node such as UI controls or groups of nodes added to a layout container.
The Image Class
48
The ImageView Class
49