SlideShare a Scribd company logo
Java Programming (CoSc3053)
/
Advanced Programming (ITec3052)
JavaFX
Java GUI
• There are three different ways to work with GUI in Java
• Abstract Window Toolkit (AWT)
• Is the original GUI system of Java
• Swing
• It was a response to deficiencies to present in the Java’s original GUI system (AWT)
• Two key features of Swing that avoid the limitation of AWT
• Swing Components are lightweight – AWT’s are heavyweight
• A lightweight component is a java component that is not dependent on the corresponding platform
component (Peer)
• Supports Pluggable Look and Feel (PLAF)
• Look and Feel of the GUI can simply be applied since Swing components are lightweight
• Consistent look and feel across different platforms due to same reason
• JavaFX
• Is the latest way to create GUI applications in Java
• According to Oracle, “JavaFx is a set of graphics and media packages that enables developers to
design, create, test, debug, and deploy rich client applications that operate consistently across
diverse platform and devices”
• It contains all the features in a single library (API) – features such as media, UI controls, web, 2D
graphics, 3D graphics, animations,
JavaFX Program Structure
• The basic structure of a JavaFX program looks like as follows
import javafx.application.Application;
import javafx.stage.Stage;
public class BasicStructure extends Application{
public void start(Stage primaryStage){
primaryStage.show();
}
public static void main(String[] args){
launch(args);
}
}
• The class needs to be a subclass of Application class
• The start() method is needed
• The main() method is also needed
• Call launch() method in the main method
• The Stage object is equivalent to a window
• To display other GUI elements in the window an object of type Scene is needed
• Demonstrated in the next program
JavaFX Program Structure
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;
public class SceneBuilder extends Application {
@Override
public void start(Stage primaryStage) {
Ellipse e = new Ellipse(100,50);
e.setFill(Color.LIGHTBLUE);
StackPane root = new StackPane();
root.getChildren().addAll(e);
Scene scene = new Scene(root, 300, 200, Color.LIGHTGREEN);
primaryStage.setTitle("Example App");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
JavaFX Architecture
• A JavaFX program needs to
• Have a Stage object – the window
• A Scene object – which will contain all the nodes hierarchically
• A GUI element in JavaFX is called node since all displayable elements extend the Node class
• Scene Graph – the hierarchical organization of nodes in the scene object
• A node in the scene graph has exactly one parent and may contain other nodes
• A node can be a leaf node with no children
• Parent node
• Manages their children by arranging them within the scene using specific layout mechanism
(Layout panes)
• Or is a container for its children (Containers)
• JavaFX uses a two-dimensional coordinate system for 2D graphics with the origin at
the upper-left corner of the window
JavaFX Architecture
• The nodes of JavaFX can be
• Graphical objects
• UI controls
• Containers
• Media Elements
• The important packages of JavFX are
•
javafx.animation – classes for doing animations
javafx.application
javafx.event – event handling classes
javafx.stage
javafx.scene
javafx.scene.shape – classes for graphical shapes such as circle, rectangle, …
javafx.scene.control – classes for UI controls such as Button, TextField, ….
javafx.scene.paint – classes for Coloring
javafx.scene.image – classes to work with images
javafx.scene.media – classes to work with audio/video
javafx.scene.layout – classes for arranging nodes in a specific way
javafx.scene.chart – classes for charting – bar chart, line chart, …
JavaFX UI Controls
• The UI control classes are found in the javafx.scene.control package
• The event handling package is in the javafx.event package
• To use UI control nodes
• Import them – the UI nodes you want
• Create an object for each UI control node
• Configure each node (size, text, color)
• Make event handling if necessary – for example, ActionEvent for a button (equivalent to button
click event)
• Add it to the layout container or directly to the scene
• Add the layout object to the scene
• Add the scene to the stage
• Show the stage
JavaFX UI Controls
• To handle events
• Identify which type of event to handle for the UI node (for example, ActionEvent of Button,
key pressed event of TextArea, etc)
• Refer to the JavaFX API reference to identify which node has which set of events
• Call the set method for the event you are handling (setOnAction() method for a button
click)
• This method accepts either
• An EventHandler object
• Or a lambda
• Using an EventHandler object
bt.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
//do what you want to do when the button is clicked
}
});
• Using lambda – which is simpler
bt.setOnAction(event -> {
//do what you want to do when the button is clicked
});
Note:- Refer what lambda syntax is in Java
JavaFX UI Controls
• There are many UI controls such as
• To use any of them
• Create an object of it
• Configure it
• Handle the appropriate event
• Add it to the scene
Alert
Button
CheckBox
ColorPocker
ComboBox
DatePicker
Label
ListView
Menu
MenuBar
MenuItem
PasswordField
ProgressBar
RadioButton
TextArea
TextField
ScrollBar
ScrollPane
Tab
ToolBar
ButtonBar
JavaFX UI Controls
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class SimpleCalculator extends Application {
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Add");
Alert a = new Alert(Alert.AlertType.INFORMATION);
TextField tf1 = new TextField();
TextField tf2 = new TextField();
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
int sum = Integer.parseInt(tf1.getText()) +
Integer.parseInt(tf2.getText());
a.setHeaderText("Information");
a.setContentText("The sum of the two numbers is: " + sum);
a.show();
}
});
FlowPane root = new FlowPane();
root.getChildren().addAll(tf1, tf2, btn);
Scene scene = new Scene(root, 500, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
JavaFX UI Controls – Menu controls
• To work with menus, the following classes form the javafx.scene.control package are used
• MenuBar, Menu, MenuItem – are the basic classes for basic Menu GUI
• CheckMenuItem, RadioMenuItem, SeparatorMenuItem – are types of menu items that you may want in
occasions
• To work with basic menu GUI
• Create an object of MenuBar
MenuBar mBar = new MenuBar();
• Create objects of Menu
• Menu fileMenu = new Menu(“File”);
Menu editMenu = new Menu(“Edit”); //create as many menus as you like
• Create objects of MenuItem
• MenuItem open = new MenuItem(“Open”);
MenuItem exit = new MenuItem(“Exit”); //create menu items for each menu
MenuItem copy = new MenuItem(“Copy”);
• Add the menu items into the corresponding Menu
• fileMenu.getItems().addAll(open, exit);
• editMenu.getItems().add(copy);
• Add the menus into the menu bar
• mBar.getMenus().addAll(fileMenu, editMenu);
• Add the menu bar into the scene at the appropriate location (top of the scene) – use layout
JavaFX UI Controls – Menu controls
• To handle event to do something when a menu item is clicked
• Use the setOnAction() method – similarly as used with button
• Either use the EventHandler object or the lambda
• Using lambda is simpler
•
exitItem.setOnAction( event -> {
Platform.exit(); //System.exit(0);
});
• The Platform class is found in the javafx.application package
• Using the EventHandler
•
exitItem.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent e){
Platform.exit();
}
});
• Do it for each of the menu items
JavaFX UI Controls – Menu controls
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuDemo extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane bp = new BorderPane();
MenuBar menuBar = new MenuBar();
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
MenuItem openItem = new MenuItem("Open");
MenuItem exitItem = new MenuItem("Exit");
MenuItem copyItem = new MenuItem("Copy");
fileMenu.getItems().addAll(openItem, exitItem);
editMenu.getItems().add(copyItem);
menuBar.getMenus().addAll(fileMenu, editMenu);
exitItem.setOnAction(event -> {
Platform.exit();
});
bp.setTop(menuBar);
Scene scene = new Scene(bp, 300, 250);
primaryStage.setTitle("Menu Demo!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
JavaFX UI Controls – Tab control
• To create a tabbed scene, use the TabPane and Tab classes
• Create an object of TabPane
• Create objects of Tab depending the number of tabs needed
• Create the UI controls to be added to each tabs
• These UI controls can be organized using layout panes
• Add the tabs to the TabPane object created
• Add the UI controls to each of the tabs
JavaFX UI Controls – Tab control
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class TabDemo extends Application {
@Override
public void start(Stage primaryStage) {
TabPane root = new TabPane();
Tab tabOne = new Tab("First");
Tab tabTwo = new Tab("Second");
Tab tabThree = new Tab("Third");
Button btn = new Button("In the First Tab");
TextField tf = new TextField("I am in the second tab");
TextArea ta = new TextArea("I am in the third tab n and I am a text
area");
root.getTabs().addAll(tabOne, tabTwo, tabThree);
tabOne.setContent(btn);
tabTwo.setContent(tf);
tabThree.setContent(ta);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
JavaFX Layout
• Layout is used to organize nodes in the scene
• The javafx.scene.layout package provides the classes for layout
• StackPane
• Stacks its children from back to front in the order they are added to the stack pane layout object
• FlowPane
• Organizes its children in either horizontal or vertical flow – horizontal is default
• BorderPane
• Divides the scene into sections top, bottom, left, right, and center so that nodes are added into each section
• GridPane
• Organizes nodes in a two-dimensional grid (in a tabular form) – a node can span columns and/or rows
• TilePane
• Similar to FlowPane except, TilePane gives equal sized space for each node
• AnchorPane
• A way to organize elements by placing them in a specific location you like
• VBox
• To organize nodes only vertically
• HBox
• To organize nodes only horizontally
• A layout can be added to another layout – e.g. a vbox can be in hbox to make a grid like layout
FlowPane Layout
• When creating an object of it, you can specify
orientation
• FlowPane fp = new FlowPane(Orientation.VERTICAL);
• The default is horizontal
• The Orientation class in the javafx.geometry package
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class FlowPaneDemo extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Get Text");
Label lb = new Label("Your name please");
TextField tf = new TextField();
btn.setOnAction(event ->
System.out.println(tf.getText()));
FlowPane fp = new FlowPane();
fp.getChildren().addAll(btn, lb, tf);
Scene scene = new Scene(fp, 400, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
BorderPane Layout
• Create an object of it
• BorderPane bp = new BorderPane();
• Use the methods to add nodes to the sections
• setTop(), setBottom(), setCenter(), setLeft(), setRight()
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BorderPaneDemo extends Application {
@Override
public void start(Stage primaryStage) {
Button btTop = new Button();
btTop.setText("Top");
Button btLeft = new Button("Left");
Button btRight = new Button("Right");
TextField tf = new TextField();
TextArea ta = new TextArea();
BorderPane root = new BorderPane();
root.setTop(btTop);
root.setBottom(tf);
root.setCenter(ta);
root.setLeft(btLeft);
root.setRight(btRight);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("BorderPane Demo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
GridPane Layout
• enables you to create a flexible grid of rows and columns in
which to lay out nodes
• Nodes can be placed in any cell in the grid and can span cells
as needed
• is useful for creating forms or any layout that is organized in
rows and columns
• The total number of rows/columns does not need to be
specified up front as the GridPane will automatically
expand/contract the grid to accommodate the content
• Cell size is automatically computed according to the sizes of
the nodes placed inside the cell
• Window (stage) size is automatically calculated if the width
and height are not specified when the Scene object is
created
• Importing the GridPane class is as follows
• import javafx.scene.layout.GridPane;
GridPane Layout
• The constructor to create GridPane object is
GridPane()
• The two overloaded methods to add a node into the grid pane are
• public void add(Node child, int columnIndex, int rowIndex)
• public void add(Node child, int columnIndex, int rowIndex, int colspan, int rowspan)
• Some the important methods are
• setHalignment(Node child, HPos value) – used to set the horizontal alignment of a node after the node is
added to the grid – this method is static (it can only be accessed as GridPane.setHalignment())
• setValignment(Node child, VPos value) – used to set the vertical alignment of a node after the node is
added to the grid – this method is static (it can only be accessed as GridPane.setValignment())
• setHgap(double value) – used to set the horizontal gap between the cells in a row (it is accessed using an
instance of GridPane - obj.setHgap())
• setVgap(double value) – used to set the vertical gap between the cells in a column (it is accessed using an
instance of GridPane - obj.setVgap())
• The VPos and HPos are classes found in the javafx.geometry package
• VPos.TOP, VPos.CENTER, VPos.BOTTOM are the possible values for the VPos
• HPos.LEFT, HPos.RIGHT, HPos.CENTER are the possible values for the HPos
GridPane Layout
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class GridPaneDemo1 extends Application {
public void start(Stage primaryStage) {
Label lblName = new Label("Your Name:");
Label lblFName = new Label("Father Name:");
Label lblAge = new Label("Your Age:");
TextField txtName = new TextField();
TextField txtFName = new TextField();
TextField txtAge = new TextField();
Button btn = new Button("Insert");
GridPane root = new GridPane();
root.setHgap(5);
root.setVgap(5);
root.add(lblName, 0, 0);
root.add(txtName, 1, 0);
root.add(lblAge, 0,2);
root.add(lblFName, 0, 1);
root.add(txtFName, 1, 1);
root.add(txtAge, 1, 2);
root.add(btn, 0, 3, 3, 1);
GridPane.setHalignment(btn, HPos.RIGHT);
Scene scene = new Scene(root);
primaryStage.setTitle("Using Grid Pane");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Hierarchical Layout
• A layout node can be used inside another layout node
• The following example uses a BorderPane as a root and then
• Add a menu bar directly on the top of the pane
• A StackPane is added into the center section of the border pane
• The stack pane contains a stack of a rectangle, a text, and a button from back to front
• A FlowPane is added to the left section of the border pane
• The flow pane uses a vertical orientation and a vertical center alignment to include the three
buttons
• Important Notes:-
• A node instance (child) cannot be repeatedly added in the scene unless removed
and added again
• A layout pane can be included in the cell of a GridPane
Hierarchical Layout
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class LayoutHierarchyDemo extends Application {
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(150, 70,Color.BROWN);
Button btn = new Button();
Text txt = new Text("I am on top of rectangle");
btn.setText("I am Front");
StackPane sp = new StackPane();
sp.getChildren().add(rect);
sp.getChildren().add(txt);
sp.getChildren().add(btn);
MenuItem menuItem = new MenuItem("Exit");
menuItem.setOnAction(event -> System.exit(0));
Menu menu = new Menu("File", null, menuItem);
//menu.getItems().add(menuItem); can also be used
MenuBar menuBar = new MenuBar(menu);
//menuBar.getMenus().add(menu) can also be used
Button bt1 = new Button("Button One");
Button bt2 = new Button("Button Two");
Button bt3 = new Button("Button Three");
Hierarchical Layout
FlowPane fp = new FlowPane(Orientation.VERTICAL);
fp.setAlignment(Pos.CENTER);
fp.getChildren().addAll(bt1, bt2, bt3);
BorderPane bp = new BorderPane();
bp.setTop(menuBar);
bp.setLeft(fp);
bp.setCenter(sp);
Scene scene = new Scene(bp, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
• Other layout classes in
javafx.scene.layout
• AnchorePane
• TilePane
• SplitPane
• HBox
• VBox
• ButtonBar
No Layout
• What if you don’t want to use any of the layout panes provided by JavaFX?
• You can use the class called Group if you want to handle the placement of
nodes by yourself.
• Group, by default, places all of its children at the origin (0,0) – the upper-left corner
of the scene
• As a result, you need to make yourself to the coordinate system of the scene
• X increases from left to right
• Y increases from top to bottom
• To use the Group class
• Import it from the javafx.scene package as import javafx.scene.Group;
• Then create an object of it as Group var = new Group();
• Then add nodes to the object created
• Then add the group object to the scene as a parent of the nodes
No Layout
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.stage.Stage;
public class NoLayoutDemo extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("I am a button");
CheckBox cb = new CheckBox("I am a check box");
cb.setLayoutX(185);
cb.setLayoutY(230);
Group root = new Group();
root.getChildren().add(btn);
root.getChildren().add(cb);
Scene scene = new Scene(root, 300, 250);
scene.setOnMouseClicked(value -> {
btn.setLayoutX(value.getX() - btn.getWidth() / 2);
btn.setLayoutY(value.getY() - btn.getHeight() / 2);
});
primaryStage.setTitle("No Layout Demo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
JavaFX Color
• Import it as import javafx.scene.paint.Color;
• There are different ways to set the color of a node in javafx
• Using the 147 predefined colors like Color.RED
• Using rgb hexadecimal values
• Using rgb decimal values
• You can optionally provide an alpha value for transparency
• 0 – fully transparent
• 1 – fully opaque
• The ff shows these three different ways to fill a rectangle
Rectangle r = new Rectangle(60, 40);
r.setFill(Color.LIGHTBLUE);//fully opaque
r.setFill(Color.web("#ADD8E6"));
r.setFill(Color.web("#ADD8E680"));//.5 opaque
r.setFill(Color.rgb(173, 216, 230));//fully opaque
r.setFill(Color.rgb(173, 216, 230,.5));//0.5 opaque
JavaFX Text
• A text is a shape with additional properties such as font, text alignment,
text, and wrapping width
• Import it from javafx.scene.text
Text text = new Text("Hi there");
text.setFill(Color.RED);
text.setFont(Font.font("Arial", 30));
text.setX(25);
text.setY(200);
• Font class is found in the javafx.scene.text
CSS Styling
• -fx prefix is used for the properties to clearly distinguish them from web ones
and avoid any compatibility issues
• JavaFX node classes have their selector counterparts, with naming convention
being lowercase class name, with words separated by hyphens
• For Button – the selector is button
• For ListView – the selector is list-view
• For the root of the scene – the selector is root
• Etc
• You are also allowed to use selectors based on custom style classes
• Then you need to add the custom style class to the node you want to apply the style class
• The third way is to use selectors based on Object ID
• Use the setId(String value) method to set an id for the node
• Then use this id in you css as a selector
• The fourth way is to use the setStyle(String value) method in the javafx code.
CSS Styling
• Except the last option (using the setStyle() method) – the css needs to be
specified in a separate css file (for example, style.css)
• This file have to be stored in the build folder (with the bitecode files of the package that
uses the css file)
• Then this file needs to be loaded as follows
• scene.getStyleSheets().add(
getClass().getResource(“filename.css”).toExternalForm()
);
• If the css file is on a remote computer over the internet, use the following to
load it
• scene.getStyleSheets().add(“http://www.someaddress.com/file.css”);
• It is also possible to apply global stylesheets to the whole application
• Application.setUserAgentStyleSheet()
• JavaFX provides two default stylesheets, which are defined as constants
• Application.setUserAgentStyleSheet(STYLESHEET_CASPIAN); //javafx 2 and before
• Application.setUserAgentStyleSheet(STYLESHEET_MODENA);//default since JavaFX 8
CSS Styling – Selectors by class name of the nodes
.root {
-fx-background-color: white;
-fx-padding: 20px;
}
.label {
-fx-background-color: black;
-fx-text-fill: white;
-fx-padding: 10px;
}
.button {
-fx-background-color: blue;
-fx-text-fill: red;
}
.list-view{
-fx-background-color: lightgrey;
-fx-pref-width: 250px;
}
• Save it into, for example, style.css in
the folder where the bytecode is
stored
• Then call scene.getStyleSheets.add()
as described in the previous slide
• The root selector is applied to the
root node
• The label selector is applied to
every Label in the scene,
• the button for every Button and
• the list-view for every ListView
node
CSS Styling – Custome style class selector
.make-it-bold{
-fx-font-weight:bold ;
}
.make-it-italic{
-fx-font-style:italic;
}
• Save it, for example, in style.css
• Load this file as described previously
• Then call the following method on the node you want to apply any of the
custom class
• .getStyleClass().add(“make-it-bold”);
CSS Styling – Selector based on ID and using setStyle
• Selector based on ID
#big-bold-label {
-fx-font-weight: bold;
-fx-font-size: 20pt;
}
• Save the stylesheet file appropriately
and load it as we did it previously
• In this case, you need to set the id of
the node you want to any one of the
ids specified in the css
• .setId(“big-bold-label)
• You can directly specify the style for
a node
• On the node you want, call the
setStyle method as follows
• .setStyle(
“-fx-background-color:black;” +
“-fx-text-fill:white;”)
• You can specify as many styles as
you need once
• The concatenation is for clarity – the
string can be one big string
Scene Builder and FXML
• Instead of writing all the code for creating GUI nodes, JavaFX provides two
important tools
• FXML (FX Markup Language)
• Similar to XML
• Used to specify the nodes of the graph scene without writing java code
• SceneBuilder
• An application used to design the graph scene
• By dragging and dropping UI elements into the graph scene without writing code
• Then saving the designed scene graph into an FXML file (a file with extension of .fxml)
• Download it and use it for free
• After generating the fxml file, you can put it in your project appropriate
directory
• Then generate a controller class – use the IDE (that you use) to generate this control
class
• We will see how using the Net Beans IDE
Scene Builder and FXML
Scene Builder and FXML
• Save it into the directory where your project is
• For example, save it as example.fxml
• On the IDE of your choice, generate the control class, in the Net Beans case
• Right click on the example.fxml and click on Make Controller form the pop up menu
• The controller is where some java code is written (for example, event handling,
property binding, animation)
• All the design is done for us by Scene Builder application using FXML
• To add it to the scene
• Parent pa = FXMLLoader.load(getClass().getResource(“example.fxml”);
• Then add the pa object to a layout and to the scene
Scene Builder and FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-
Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Button layoutX="158.0" layoutY="117.0" mnemonicParsing="false"
text="Button" />
<CheckBox layoutX="137.0" layoutY="211.0" mnemonicParsing="false"
text="CheckBox" />
<MenuBar layoutX="14.0" layoutY="14.0">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</AnchorPane>
Properties and Bindings
• Property binding is a mechanism that enables to update one property when
another property changes
• A property is an attribute of a class that you can read or write
• A property has a getter and setter that perform the read and write respectively
• In JavaFX a property has a third method, in addition to getter and setter
methods
• This method returns an object implementing the Property interface
• For example, a JavaFX text property has the following three methods
• String getText()
• void setText(String text)
• Property<String> textProperty()
• A listener can be attached to the Property object
• Moreover, in JavaFX, to work with property binding
• The property must be defined using the built-in classes provided by JavaFX
• The javafx.beans.property package contains all the classes important for creating
properties that automatically support property binding
Properties and Bindings
• The classes in javafx.beans.property
For Primitive Types For Object Types
StringProperty
SimpleStringProperty
IntegerProperty
SimpleIntegerProperty
FloatProperty
SimpleFloatProperty
LongProperty
SimpleLongProperty
DoubleProperty
SimpleDoubleProperty
BooleanProperty
SimpleBooleanProperty
ListProperty<E>
SimpleListPropery<E>
MapProperty<K,V>
SimpleMapProperty<K,V>
SetProperty<E>
SimpleSetProperty<E>
ObjectProperty<T>
SimpleObjectProperty<T>
Properties and Bindings
• The need to create properties using these classes is to simply attach a
listener that will be invoked whenever a property’s value is changed
• There are two way
• Using ChangeListener or
• Using InvalidationListener
• To demonstrate how consider
the Greeting class
import javafx.beans.property.StringProperty;
import javafx.beans.property.SimpleStringProperty;
public class Greeting {
private StringProperty text = new SimpleStringProperty("");
public final StringProperty textProperty() {
return text;
}
public final void setText(String text) {
this.text.set(text);
}
public final String getText(){
return text.get();
}
}
Properties and Bindings
• After creating an object of Greeting class
• You can attach a listener using the InvalidationListener
Greeting g = new Greeting();
g.setText(“Old Value”);
g.textProperty().addListener(event->{
System.out.println(“The new value of greeting is: ’”+ g.getText()+”’”);
});
g.setText(“A new value”)
• You can also use the ChangeListener as follows
g.setText(“Old Value”);
g.textProperty().addListener((property, oldValue, newValue)->{
System.out.println(“The new value of greeting is: ’”+ newValue +”’”);
});
g.setText(“A new value”)
• In either case, whenever the value of the property is changed, an event is triggered that
displays the new value on to the console
• The main purpose of attaching a listener is for Binding
• Binding – making a property to change its value whenever another property’s value is changed
• For example, whenever the value of a TextField is changed, change the value of a Label or another
node or another object and vice versa
Properties and Bindings
• The nodes of the JavaFX API has properties that are designed to support binding
automatically
• For example, the TextField has a textProperty, disableProperty, editableProperty,
alignmentProperty, ……
• The same is true for every other nodes of JavaFX
• You can also define your own classes that support property binding using the classes found
in the javafx.beans.property package
• To make binding on the nodes call either the bind() or binBidirectional() method
as follows
• When the value of tf2 changes, the value of tf1 is replaced by the value of tf2
TextField tf1 = new TextField();
TextField tf2 = new TextField();
tf1.textProperty().bind(tf2.textProperty());
• The bind() method is used to force unidirectional binding (from tf2 to tf1 in the
case of this example)
Properties and Bindings
• Two way binding can also be implemented as follows
TextField tf1 = new TextField();
TextField tf2 = new TextField();
tf1.textProperty().bindBidirectional(tf2.textProperty());
• In the case of bindBidirectional() change is reflected in both direction (from tf1 to tf2
and also from tf2 to tf1)
• Note: the nodes needs not be of same type
• However, the properties must be compatible or you need to perform some computation before the
binding occurs
• For this purpose, there is a class called Bindings that contain static methods to perform some
computation
• tf1.textProperty().bind(Bindings.concat(“From TF2 - ”, tf2.textProperty());
• The Bindings class is found in the javafx.beans.binding package
• You may also import it as static and use it as follows
• import static javafx.beans.binding.Bindings.*;
• tf1.textProperty().bind(concat(“From TF2 – “, tf2.textProperty());
• There are many methods available in the Bindings class
• add, subtract, multiply, divide, max, min, greaterThan, greaterThanOrEqual, lessThan,
lessThanOrEqual, equal, notEqual, equalIgnoreCase, notEqualIgnoreCase, ……
Properties and Bindings – Example
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
public class Data {
private DoubleProperty value = new SimpleDoubleProperty(0);
public final DoubleProperty valueProperty(){
return value;
}
public final void setValue(double v){
value.set(v);
}
public final double getValue(){
return value.get();
}
}
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class PropertyBindingDemo1 extends Application {
public void start(Stage primaryStage) {
Data data = new Data();
Button btn = new Button();
btn.setText("Increase");
ProgressBar pBar = new ProgressBar();
ProgressIndicator pIndicator = new ProgressIndicator();
Properties and Bindings – Example
btn.setOnAction(event -> {
if (data.getValue() < 100) {
data.setValue(data.getValue() + 5);
}
});
Button btn1 = new Button("Decrease");
btn1.setOnAction(event -> {
if (data.getValue() > 0) {
data.setValue(data.getValue() - 5);
}
});
Bar.progressProperty().bind(Bindings.divide(data.valueProperty(), 100));
pIndicator.progressProperty().bind(pBar.progressProperty());
GridPane root = new GridPane();
root.add(pBar, 0, 0);
root.add(pIndicator, 1, 0);
root.add(btn, 0, 1);
root.add(btn1,1,1);
Scene scene = new Scene(root);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Properties and Bindings – Centering a node when the
scene resizes
• Using the following will make the rectangle at center at the
beginning; but when the window resizes, the rectangle will
no longer be at the center
rect.setX(scene.getWidth()/2 - rect.getWidth()/2);
rect.setY(scene.getHeight()/2 - rect.getHeight()/2);
• The following program, using property binding, make the
rectangle at the center what ever the size of the scene is
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class PropertyBindingDemo2 extends Application {
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100,100,Color.SKYBLUE);
Group root = new Group();
root.getChildren().add(rect);
Scene scene = new Scene(root, 300, 250);
rect.xProperty().bind(Bindings.subtract(
Bindings.divide(scene.widthProperty(), 2),
Bindings.divide(rect.widthProperty(), 2))
);
rect.yProperty().bind(Bindings.subtract(
Bindings.divide(scene.heightProperty(), 2),
Bindings.divide(rect.heightProperty(), 2))
);
primaryStage.setTitle("Centering upon resize");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Graphics and Animation
• JavaFX provides set of classes that enable us to work with graphics
• The javafx.scene.shape package provides classes to work with shapes
• All classes in this package are subclasses of the class Shape
(javafx.scene.shape.Shape) – which in turn is a subclass of the Node class
(javafx.scene.Node)
• Some of the common classes in this package are
• Line, Rectangle, Arc, Circle, Ellipse, Path, Polygon, Polyline, etc
• JavaFX also provides a library for making animations
• The package containing the classes for animation is javafx.animation
• There are predefined animation classes to use such as
• FadeTransition, PathTransition, ScaleTransition, TranslateTransition, etc.
• Or, you can do things by yourself using the classes
• KeyValue, KeyFrame, TimeLine, etc.
Graphics and Animation – Drawing Line
• The class for drawing line is javafx.scene.shape.Line
• There are two ways
• Creating a line object by specifying the start and end coordinates of the line as follows – a
line from (200, 30) to (100, 50)
Line line = new Line(200, 30 , 100, 50);
• The second way is to create an object without the points and use the setter methods to set
the point
Line line = new Line();
line.setStartX(200);
line.setStartY(30);
line.setEndX(100);
line.setEndY(50);
• By default,
• Line nodes have a stroke width of 1.0 and a stroke color of black (Color.BLACK)
• Then, use the properties inherited from the Shape class to create different kinds
of lines
Graphics and Animation – Drawing Line
• The Shape class provides the following properties
• fill – a color to fill inside a shape
• strokeDashOffset – the offset (distance) into the dashed pattern (between repeated
pattens)
• strokeLineCap – the cap style on the end of a line or path
• strokeLineJoin – decoration when lines meet
• stroke – a color of the shape’s line stroke
• strokeType – where to draw the stroke around the boundary of a Shape node –
center, outside or inside
• strokeWidth – a stroke lines width
Graphics and Animation – Drawing Line
public void start(Stage primaryStage) {
Line line = new Line(200,30,100,30);
line.setStroke(Color.RED);
line.getStrokeDashArray().addAll(15d);
line.setStrokeDashOffset(0);
line.setStrokeWidth(3);
StackPane root = new StackPane();
root.getChildren().add(line);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Line Demo");
primaryStage.setScene(scene);
primaryStage.show();
}
Graphics and Animation – Drawing Rectangle
• The javafx.scene.shape.Rectangle inherits the same methods from the
javafx.scene.shape.Shape class
• To draw a rectangle, the constructors are
• Rectangle()
• Rectangle(width, height)
• Rectangle(width, height, fillColor)
• Rectangle(xLocation, yLocation, width, height)
• Use any of the constructor and then modify the properties as you like; some of the set
methods are
• setX(), setY(), setWidth(), setHeight(), setFill(), setArcWidth(), setArkHeight()
• The last two are used to create a round rectangle
Rectangle roundRect = new Rectangle();
roundRect.setX(50);
roundRect.setY(50);
roundRect.setWidth(100);
roundRect.setHeight(130);
roundRect.setArcWidth(10);
roundRect.setArcHeight(40);
• Shapes such as Ellipse, Circle, Polygon can be easily drawn in a similar fashion
Graphics and Animation – Complex Shapes
• CubicCurve
• To draw graphics which looks as a sign wave
• Use the following constructor
CubicCurve cubic = new CubicCurve(startX, startY, controlx1, controly1, controlx2, controly2, endx,
endy)
• QuadCurve – similar to the CubicCurve but with only one control point
• Use the following constructor
• QuadCurve quadC = new QuadCurve(startX, startY, controlX, controlY, endX, endY)
Graphics and Animation – Complex Shapes
public void start(Stage primaryStage) {
Group g = new Group();
CubicCurve cubic = new CubicCurve(50, 50, 75, 0, 125, 100, 150, 50);
cubic.setFill(Color.WHITE);
cubic.setStroke(Color.BLACK);
cubic.setStrokeWidth(3);
QuadCurve quad = new QuadCurve(50, 200, 75, 50, 100, 200);
quad.setFill(Color.WHITE);
quad.setStroke(Color.BLACK);
quad.setStrokeWidth(3);
Scene scene = new Scene(g, 300, 250);
g.getChildren().add(cubic);
g.getChildren().add(quad);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
Graphics and Animation – Complex Shapes
• Path
• Is a class used to draw any shape you want by combining points called path
elements
• These path elements are a subclass of the class PathElement
• The following are the path elements
• LineTo
• MoveTo
• QuadCurveTo
• CubicCurveTo
• The path elements are not subclass of the Node class – as a result they cannot be
child nodes in the scene graph
• Instead, they are added to the Path object in the order we need the shape to draw.
Graphics and Animation – Complex Shapes
public void start(Stage primaryStage) {
Path p = new Path();
MoveTo mt = new MoveTo(50, 50);
LineTo lt = new LineTo(150, 50);
LineTo lt1 = new LineTo(100, 125);
LineTo lt3 = new LineTo(50, 50);
p.getElements().addAll(mt, lt, lt1, lt3);
AnchorPane root = new AnchorPane();
root.getChildren().add(p);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
Graphics and Animation - Canvas
• JavaFX has a complete set of controls for use and allows developers to style their
applications using CSS
• Among all the controls provided by JavaFX, we have the powerful Canvas – higher
performance graphics
• Used to create visually impressive graphics applications that make use of JavaFX hardware
acceleration graphics
• Imagine that
• You were given the task of creating a JavaFX game or
• You have to build a simulation or
• You have to build some other kind of application that requires continuous update of the
screen
• For such cases, the Canvas is used instead of the standard UI control APIs
• it doesn’t mean that you cannot use the standard control UI to do so
• The package containing the Canvas class is javafx.scene.canvas
• The Canvas class, like all other JavaFX nodes, it is a subclass of Node
Graphics and Animation - Canvas
• To work with Canvas
• Create an object of the canvas class – Canvas canvas = new Canvas();
• Set the width and height of the canvas – canvas.setWidth(400);
• Get the 2D graphics context of the canvas – GraphicsContext graphicsContext2D = canvas.getGraphicsContext2D();
• Then using the methods of the GraphicsContext object, you can draw anything you want
• Add the canvas object to one of the layout pane
• Add the layout pane object to the scene object
• Add the scene object to the stage
• Some of the methods of the GraphicsContext object are
• setFill()
• setStroke()
• fillRect()
• fillOval()
• fillRoundRect()
• fillText()
• setLineWidth()
• setTextAlign()
• setFont()
• Etc
• Using these and other methods you can draw graphics on the canvas
Graphics and Animation - Canvas
public void start(Stage primaryStage) {
Canvas c = new Canvas();
c.setWidth(300);
c.setHeight(300);
GraphicsContext gc = c.getGraphicsContext2D();
gc.setFill(Color.RED);
gc.fillRect(20, 20, 60, 90);
gc.setFill(Color.GREY);
gc.setStroke(Color.RED);
gc.setLineWidth(3);
gc.strokeOval(20, 150, 80, 50);
gc.fillOval(20, 210, 80, 50);
gc.strokeOval(20, 210, 80, 50);
StackPane root = new StackPane();
root.getChildren().add(c);
Scene scene = new Scene(root);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
Graphics and Animation – Animation
• The javafx.animation package provides classes to work with animation
• Allows us to assemble timed events that can interpolate over property-based values
(Property) in order to produce animated effects
• For example, to produce a fade-out effect, you would target a node’s opacity property to
interpolate its value starting from 1 (fully opaque) to 0 (transparent) over a period of time
• KeyValue class
• Defines the start and end values of a property to interpolate between
• The KeyValue object can be of type Interpolator.EASE_IN, or Interpolator.EASE_OUT, or
Interpolator.EASE_BOTH – specify any of these in the constructor
• The KeyValue class can be used as follows
Rectangle rectangle = new Rectangle(0, 0, 50, 50);
KeyValue keyValue = new KeyValue(rectangle.opacityProperty(), 0);
• KeyFrame class
• When an animation (Timeline) occurs, each timed event is called a keyframe (a KeyFrame
object)
• A KeyFrame object is responsible for interpolating key values (KeyValue objects) over a
period of time (javafx.util.Duration)
Graphics and Animation – Animation
• KeyFrame class (continued)
• Is used with KeyValue objects such as
Rectangle rectangle = new Rectangle(0, 0, 50, 50);
KeyValue xValue = new KeyValue(rectangle.xProperty(), 100);
KeyValue yValue = new KeyValue(rectangle.yProperty(), 100);
KeyFrame keyFrame = new KeyFrame(Duration.millis(1000), xValue, yValue);
• The previous code defines a keyframe to move a rectangle’s upper-left corner (0, 0) to point (100,
100) in one second or 1000 milliseconds
• Timeline class
• A Timeline is one animation sequence consisting of many KeyFrame objects
• Each KeyFrame object is run sequentially
• The Timeline class has standard attributes such as its cycle count and auto-reverse that you can set;
these attributes are inherited form javafx.animation.Animation class
• The cycle count is the number of times you want the timeline to play the animation
• The auto-reverse property is a Boolean flag to indicate that the animation can play the timeline backward (the
keyframes in reverse order)
• By default, the cycle count is set to 1, and auto-reverse is set to false
Graphics and Animation – Animation
• Timeline class (continued)
• It is used as follows
Timeline timeline = new Timeline(); //KeyFrame objects can be passed here with the constructor
timeline.setCycleCount(Timeline.INDEFINITE);//or you can specify how many times to repeate
timeline.setAutoReverse(true);
timeline.getKeyFrames().addAll(keyFrame1, keyFrame2); //this also adds KeyFrame objects
timeline.play();
• The following example demonstrates the use of KeyValue, KeyFrame,
TimeLine classes
Graphics and Animation – Animation
public class AnimationDemo extends Application {
public void start(Stage primaryStage) {
Group root = new Group();
Rectangle rectangle = new Rectangle(0, 0, 50, 50);
Rectangle rectangle1 = new Rectangle(80,0,50,50);
rectangle1.setFill(Color.BLUE);
root.getChildren().addAll(rectangle, rectangle1);
KeyValue xValue = new KeyValue(rectangle.xProperty(), 100);
KeyValue yValue = new KeyValue(rectangle.yProperty(), 100);
KeyFrame keyFrame = new KeyFrame(Duration.millis(1000), xValue, yValue);
KeyValue keyValue1 = new KeyValue(rectangle1.opacityProperty(), 0);
KeyFrame keyFrame1 = new KeyFrame(Duration.millis(1000), keyValue1);
Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
timeline.getKeyFrames().addAll(keyFrame, keyFrame1);
timeline.play();
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Graphics and Animation – Animation
• For common animation effects, javafx.animation provides predefined
classes that can be used without coding low-level using Key values, key
frames, timeline – the following are some of these classes
• FadeTransition – fade animation by changing the opacity of the node
• PathTransition – for translating a node along a predefined path
• ScaleTransition – for increasing or decreasing the size of the node
• TranslateTransition – for moving a node
• FillTransition – animation by changing the fill color of a node
• RotateTransition – rotating a node in the scene graph
• ParallelTransition – set of animations in parallel
• SequentialTransition – set of animations in sequential order
• The following program demonstrates how to use these predefined classes
Graphics and Animation – Animation
public class AnimationDemo1 extends Application {
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Ellipse e = new Ellipse(300, 50, 100, 50);
FillTransition ft = new FillTransition(Duration.millis(3000), e,
Color.RED, Color.BLUE);
ft.setCycleCount(2);
ft.setAutoReverse(true);
TranslateTransition tt = new
TranslateTransition(Duration.millis(5000),e);
tt.setToX(-100);
tt.setToY(300);
ParallelTransition pt = new ParallelTransition(ft, tt);
pt.play();
//to make it sequential comment the ParallelTransition (the
//above two statements) and uncomment the following two
//statements
//SequentialTransition st = new SequentialTransition(ft, tt);
//st.play();
Scene scene = new Scene(root, 400, 400);
root.getChildren().addAll(e);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Graphics and Animation – Animation
The End!

More Related Content

PDF
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
SakkaravarthiS1
 
PDF
JavaFx Introduction, Basic JavaFx Architecture
Jainul Musani
 
PPT
Unit 1 informatica en ingles
Marisa Torrecillas
 
PPT
Unit i informatica en ingles
Marisa Torrecillas
 
PPTX
Untitled (1)-------------------------------------------------.pptx
poojakkamakshi2006
 
PDF
Demo on JavaFX
Knoldus Inc.
 
PDF
Domain Driven Design
Knoldus Inc.
 
PDF
Introduction to JavaFX
Mindfire Solutions
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
SakkaravarthiS1
 
JavaFx Introduction, Basic JavaFx Architecture
Jainul Musani
 
Unit 1 informatica en ingles
Marisa Torrecillas
 
Unit i informatica en ingles
Marisa Torrecillas
 
Untitled (1)-------------------------------------------------.pptx
poojakkamakshi2006
 
Demo on JavaFX
Knoldus Inc.
 
Domain Driven Design
Knoldus Inc.
 
Introduction to JavaFX
Mindfire Solutions
 

Similar to JavaFXaeurwstkiryikryiuyoyiloyuikygi.pdf (20)

PPTX
JavaFX ALA ppt.pptx
BhagyasriPatel1
 
PDF
Java fx
hussein zayed
 
PDF
From Swing to JavaFX
Yuichi Sakuraba
 
PPT
GUI design using JAVAFX.ppt
TabassumMaktum
 
PDF
JavaFX for Java Developers
Sten Anderson
 
PPTX
Java AWT and Java FX
pratikkadam78
 
PDF
The Brainify App - JavaFx
Mohd Shamweel
 
PPTX
Chapter 2 JavaFX UI Controls and Multimedia.pptx
SamatarHussein
 
PDF
Java FX Part2
Mindfire Solutions
 
ODP
JavaFX in Action Part I
Mohammad Hossein Rimaz
 
PPTX
Java fx
Rohit Vaidya
 
PDF
Programming with JavaFX
Fulvio Corno
 
PPTX
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
JAX London
 
ODP
Java Fx Overview Tech Tour
Carol McDonald
 
PDF
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
PPTX
Introduction to JavaFX
Houari ZEGAI
 
PPTX
JavaFX Presentation
Mochamad Taufik Mulyadi
 
PDF
Javafxpressentation 140524053934-phpapp01 (1)
ssuser4f9de3
 
PPT
Eo gaddis java_chapter_14_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_14_5e
Gina Bullock
 
JavaFX ALA ppt.pptx
BhagyasriPatel1
 
Java fx
hussein zayed
 
From Swing to JavaFX
Yuichi Sakuraba
 
GUI design using JAVAFX.ppt
TabassumMaktum
 
JavaFX for Java Developers
Sten Anderson
 
Java AWT and Java FX
pratikkadam78
 
The Brainify App - JavaFx
Mohd Shamweel
 
Chapter 2 JavaFX UI Controls and Multimedia.pptx
SamatarHussein
 
Java FX Part2
Mindfire Solutions
 
JavaFX in Action Part I
Mohammad Hossein Rimaz
 
Java fx
Rohit Vaidya
 
Programming with JavaFX
Fulvio Corno
 
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
JAX London
 
Java Fx Overview Tech Tour
Carol McDonald
 
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
Introduction to JavaFX
Houari ZEGAI
 
JavaFX Presentation
Mochamad Taufik Mulyadi
 
Javafxpressentation 140524053934-phpapp01 (1)
ssuser4f9de3
 
Eo gaddis java_chapter_14_5e
Gina Bullock
 
Eo gaddis java_chapter_14_5e
Gina Bullock
 
Ad

Recently uploaded (20)

PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Doc9.....................................
SofiaCollazos
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Ad

JavaFXaeurwstkiryikryiuyoyiloyuikygi.pdf

  • 1. Java Programming (CoSc3053) / Advanced Programming (ITec3052) JavaFX
  • 2. Java GUI • There are three different ways to work with GUI in Java • Abstract Window Toolkit (AWT) • Is the original GUI system of Java • Swing • It was a response to deficiencies to present in the Java’s original GUI system (AWT) • Two key features of Swing that avoid the limitation of AWT • Swing Components are lightweight – AWT’s are heavyweight • A lightweight component is a java component that is not dependent on the corresponding platform component (Peer) • Supports Pluggable Look and Feel (PLAF) • Look and Feel of the GUI can simply be applied since Swing components are lightweight • Consistent look and feel across different platforms due to same reason • JavaFX • Is the latest way to create GUI applications in Java • According to Oracle, “JavaFx is a set of graphics and media packages that enables developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platform and devices” • It contains all the features in a single library (API) – features such as media, UI controls, web, 2D graphics, 3D graphics, animations,
  • 3. JavaFX Program Structure • The basic structure of a JavaFX program looks like as follows import javafx.application.Application; import javafx.stage.Stage; public class BasicStructure extends Application{ public void start(Stage primaryStage){ primaryStage.show(); } public static void main(String[] args){ launch(args); } } • The class needs to be a subclass of Application class • The start() method is needed • The main() method is also needed • Call launch() method in the main method • The Stage object is equivalent to a window • To display other GUI elements in the window an object of type Scene is needed • Demonstrated in the next program
  • 4. JavaFX Program Structure import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Ellipse; import javafx.stage.Stage; public class SceneBuilder extends Application { @Override public void start(Stage primaryStage) { Ellipse e = new Ellipse(100,50); e.setFill(Color.LIGHTBLUE); StackPane root = new StackPane(); root.getChildren().addAll(e); Scene scene = new Scene(root, 300, 200, Color.LIGHTGREEN); primaryStage.setTitle("Example App"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 5. JavaFX Architecture • A JavaFX program needs to • Have a Stage object – the window • A Scene object – which will contain all the nodes hierarchically • A GUI element in JavaFX is called node since all displayable elements extend the Node class • Scene Graph – the hierarchical organization of nodes in the scene object • A node in the scene graph has exactly one parent and may contain other nodes • A node can be a leaf node with no children • Parent node • Manages their children by arranging them within the scene using specific layout mechanism (Layout panes) • Or is a container for its children (Containers) • JavaFX uses a two-dimensional coordinate system for 2D graphics with the origin at the upper-left corner of the window
  • 6. JavaFX Architecture • The nodes of JavaFX can be • Graphical objects • UI controls • Containers • Media Elements • The important packages of JavFX are • javafx.animation – classes for doing animations javafx.application javafx.event – event handling classes javafx.stage javafx.scene javafx.scene.shape – classes for graphical shapes such as circle, rectangle, … javafx.scene.control – classes for UI controls such as Button, TextField, …. javafx.scene.paint – classes for Coloring javafx.scene.image – classes to work with images javafx.scene.media – classes to work with audio/video javafx.scene.layout – classes for arranging nodes in a specific way javafx.scene.chart – classes for charting – bar chart, line chart, …
  • 7. JavaFX UI Controls • The UI control classes are found in the javafx.scene.control package • The event handling package is in the javafx.event package • To use UI control nodes • Import them – the UI nodes you want • Create an object for each UI control node • Configure each node (size, text, color) • Make event handling if necessary – for example, ActionEvent for a button (equivalent to button click event) • Add it to the layout container or directly to the scene • Add the layout object to the scene • Add the scene to the stage • Show the stage
  • 8. JavaFX UI Controls • To handle events • Identify which type of event to handle for the UI node (for example, ActionEvent of Button, key pressed event of TextArea, etc) • Refer to the JavaFX API reference to identify which node has which set of events • Call the set method for the event you are handling (setOnAction() method for a button click) • This method accepts either • An EventHandler object • Or a lambda • Using an EventHandler object bt.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent event){ //do what you want to do when the button is clicked } }); • Using lambda – which is simpler bt.setOnAction(event -> { //do what you want to do when the button is clicked }); Note:- Refer what lambda syntax is in Java
  • 9. JavaFX UI Controls • There are many UI controls such as • To use any of them • Create an object of it • Configure it • Handle the appropriate event • Add it to the scene Alert Button CheckBox ColorPocker ComboBox DatePicker Label ListView Menu MenuBar MenuItem PasswordField ProgressBar RadioButton TextArea TextField ScrollBar ScrollPane Tab ToolBar ButtonBar
  • 10. JavaFX UI Controls import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; public class SimpleCalculator extends Application { public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Add"); Alert a = new Alert(Alert.AlertType.INFORMATION); TextField tf1 = new TextField(); TextField tf2 = new TextField(); btn.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { int sum = Integer.parseInt(tf1.getText()) + Integer.parseInt(tf2.getText()); a.setHeaderText("Information"); a.setContentText("The sum of the two numbers is: " + sum); a.show(); } }); FlowPane root = new FlowPane(); root.getChildren().addAll(tf1, tf2, btn); Scene scene = new Scene(root, 500, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 11. JavaFX UI Controls – Menu controls • To work with menus, the following classes form the javafx.scene.control package are used • MenuBar, Menu, MenuItem – are the basic classes for basic Menu GUI • CheckMenuItem, RadioMenuItem, SeparatorMenuItem – are types of menu items that you may want in occasions • To work with basic menu GUI • Create an object of MenuBar MenuBar mBar = new MenuBar(); • Create objects of Menu • Menu fileMenu = new Menu(“File”); Menu editMenu = new Menu(“Edit”); //create as many menus as you like • Create objects of MenuItem • MenuItem open = new MenuItem(“Open”); MenuItem exit = new MenuItem(“Exit”); //create menu items for each menu MenuItem copy = new MenuItem(“Copy”); • Add the menu items into the corresponding Menu • fileMenu.getItems().addAll(open, exit); • editMenu.getItems().add(copy); • Add the menus into the menu bar • mBar.getMenus().addAll(fileMenu, editMenu); • Add the menu bar into the scene at the appropriate location (top of the scene) – use layout
  • 12. JavaFX UI Controls – Menu controls • To handle event to do something when a menu item is clicked • Use the setOnAction() method – similarly as used with button • Either use the EventHandler object or the lambda • Using lambda is simpler • exitItem.setOnAction( event -> { Platform.exit(); //System.exit(0); }); • The Platform class is found in the javafx.application package • Using the EventHandler • exitItem.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ Platform.exit(); } }); • Do it for each of the menu items
  • 13. JavaFX UI Controls – Menu controls import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class MenuDemo extends Application { @Override public void start(Stage primaryStage) { BorderPane bp = new BorderPane(); MenuBar menuBar = new MenuBar(); Menu fileMenu = new Menu("File"); Menu editMenu = new Menu("Edit"); MenuItem openItem = new MenuItem("Open"); MenuItem exitItem = new MenuItem("Exit"); MenuItem copyItem = new MenuItem("Copy"); fileMenu.getItems().addAll(openItem, exitItem); editMenu.getItems().add(copyItem); menuBar.getMenus().addAll(fileMenu, editMenu); exitItem.setOnAction(event -> { Platform.exit(); }); bp.setTop(menuBar); Scene scene = new Scene(bp, 300, 250); primaryStage.setTitle("Menu Demo!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 14. JavaFX UI Controls – Tab control • To create a tabbed scene, use the TabPane and Tab classes • Create an object of TabPane • Create objects of Tab depending the number of tabs needed • Create the UI controls to be added to each tabs • These UI controls can be organized using layout panes • Add the tabs to the TabPane object created • Add the UI controls to each of the tabs
  • 15. JavaFX UI Controls – Tab control import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.stage.Stage; public class TabDemo extends Application { @Override public void start(Stage primaryStage) { TabPane root = new TabPane(); Tab tabOne = new Tab("First"); Tab tabTwo = new Tab("Second"); Tab tabThree = new Tab("Third"); Button btn = new Button("In the First Tab"); TextField tf = new TextField("I am in the second tab"); TextArea ta = new TextArea("I am in the third tab n and I am a text area"); root.getTabs().addAll(tabOne, tabTwo, tabThree); tabOne.setContent(btn); tabTwo.setContent(tf); tabThree.setContent(ta); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 16. JavaFX Layout • Layout is used to organize nodes in the scene • The javafx.scene.layout package provides the classes for layout • StackPane • Stacks its children from back to front in the order they are added to the stack pane layout object • FlowPane • Organizes its children in either horizontal or vertical flow – horizontal is default • BorderPane • Divides the scene into sections top, bottom, left, right, and center so that nodes are added into each section • GridPane • Organizes nodes in a two-dimensional grid (in a tabular form) – a node can span columns and/or rows • TilePane • Similar to FlowPane except, TilePane gives equal sized space for each node • AnchorPane • A way to organize elements by placing them in a specific location you like • VBox • To organize nodes only vertically • HBox • To organize nodes only horizontally • A layout can be added to another layout – e.g. a vbox can be in hbox to make a grid like layout
  • 17. FlowPane Layout • When creating an object of it, you can specify orientation • FlowPane fp = new FlowPane(Orientation.VERTICAL); • The default is horizontal • The Orientation class in the javafx.geometry package import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; public class FlowPaneDemo extends Application { @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Get Text"); Label lb = new Label("Your name please"); TextField tf = new TextField(); btn.setOnAction(event -> System.out.println(tf.getText())); FlowPane fp = new FlowPane(); fp.getChildren().addAll(btn, lb, tf); Scene scene = new Scene(fp, 400, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 18. BorderPane Layout • Create an object of it • BorderPane bp = new BorderPane(); • Use the methods to add nodes to the sections • setTop(), setBottom(), setCenter(), setLeft(), setRight() import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class BorderPaneDemo extends Application { @Override public void start(Stage primaryStage) { Button btTop = new Button(); btTop.setText("Top"); Button btLeft = new Button("Left"); Button btRight = new Button("Right"); TextField tf = new TextField(); TextArea ta = new TextArea(); BorderPane root = new BorderPane(); root.setTop(btTop); root.setBottom(tf); root.setCenter(ta); root.setLeft(btLeft); root.setRight(btRight); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("BorderPane Demo"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 19. GridPane Layout • enables you to create a flexible grid of rows and columns in which to lay out nodes • Nodes can be placed in any cell in the grid and can span cells as needed • is useful for creating forms or any layout that is organized in rows and columns • The total number of rows/columns does not need to be specified up front as the GridPane will automatically expand/contract the grid to accommodate the content • Cell size is automatically computed according to the sizes of the nodes placed inside the cell • Window (stage) size is automatically calculated if the width and height are not specified when the Scene object is created • Importing the GridPane class is as follows • import javafx.scene.layout.GridPane;
  • 20. GridPane Layout • The constructor to create GridPane object is GridPane() • The two overloaded methods to add a node into the grid pane are • public void add(Node child, int columnIndex, int rowIndex) • public void add(Node child, int columnIndex, int rowIndex, int colspan, int rowspan) • Some the important methods are • setHalignment(Node child, HPos value) – used to set the horizontal alignment of a node after the node is added to the grid – this method is static (it can only be accessed as GridPane.setHalignment()) • setValignment(Node child, VPos value) – used to set the vertical alignment of a node after the node is added to the grid – this method is static (it can only be accessed as GridPane.setValignment()) • setHgap(double value) – used to set the horizontal gap between the cells in a row (it is accessed using an instance of GridPane - obj.setHgap()) • setVgap(double value) – used to set the vertical gap between the cells in a column (it is accessed using an instance of GridPane - obj.setVgap()) • The VPos and HPos are classes found in the javafx.geometry package • VPos.TOP, VPos.CENTER, VPos.BOTTOM are the possible values for the VPos • HPos.LEFT, HPos.RIGHT, HPos.CENTER are the possible values for the HPos
  • 21. GridPane Layout import javafx.application.Application; import javafx.geometry.HPos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class GridPaneDemo1 extends Application { public void start(Stage primaryStage) { Label lblName = new Label("Your Name:"); Label lblFName = new Label("Father Name:"); Label lblAge = new Label("Your Age:"); TextField txtName = new TextField(); TextField txtFName = new TextField(); TextField txtAge = new TextField(); Button btn = new Button("Insert"); GridPane root = new GridPane(); root.setHgap(5); root.setVgap(5); root.add(lblName, 0, 0); root.add(txtName, 1, 0); root.add(lblAge, 0,2); root.add(lblFName, 0, 1); root.add(txtFName, 1, 1); root.add(txtAge, 1, 2); root.add(btn, 0, 3, 3, 1); GridPane.setHalignment(btn, HPos.RIGHT); Scene scene = new Scene(root); primaryStage.setTitle("Using Grid Pane"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 22. Hierarchical Layout • A layout node can be used inside another layout node • The following example uses a BorderPane as a root and then • Add a menu bar directly on the top of the pane • A StackPane is added into the center section of the border pane • The stack pane contains a stack of a rectangle, a text, and a button from back to front • A FlowPane is added to the left section of the border pane • The flow pane uses a vertical orientation and a vertical center alignment to include the three buttons • Important Notes:- • A node instance (child) cannot be repeatedly added in the scene unless removed and added again • A layout pane can be included in the cell of a GridPane
  • 23. Hierarchical Layout import javafx.application.Application; import javafx.geometry.Orientation; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; public class LayoutHierarchyDemo extends Application { public void start(Stage primaryStage) { Rectangle rect = new Rectangle(150, 70,Color.BROWN); Button btn = new Button(); Text txt = new Text("I am on top of rectangle"); btn.setText("I am Front"); StackPane sp = new StackPane(); sp.getChildren().add(rect); sp.getChildren().add(txt); sp.getChildren().add(btn); MenuItem menuItem = new MenuItem("Exit"); menuItem.setOnAction(event -> System.exit(0)); Menu menu = new Menu("File", null, menuItem); //menu.getItems().add(menuItem); can also be used MenuBar menuBar = new MenuBar(menu); //menuBar.getMenus().add(menu) can also be used Button bt1 = new Button("Button One"); Button bt2 = new Button("Button Two"); Button bt3 = new Button("Button Three");
  • 24. Hierarchical Layout FlowPane fp = new FlowPane(Orientation.VERTICAL); fp.setAlignment(Pos.CENTER); fp.getChildren().addAll(bt1, bt2, bt3); BorderPane bp = new BorderPane(); bp.setTop(menuBar); bp.setLeft(fp); bp.setCenter(sp); Scene scene = new Scene(bp, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } • Other layout classes in javafx.scene.layout • AnchorePane • TilePane • SplitPane • HBox • VBox • ButtonBar
  • 25. No Layout • What if you don’t want to use any of the layout panes provided by JavaFX? • You can use the class called Group if you want to handle the placement of nodes by yourself. • Group, by default, places all of its children at the origin (0,0) – the upper-left corner of the scene • As a result, you need to make yourself to the coordinate system of the scene • X increases from left to right • Y increases from top to bottom • To use the Group class • Import it from the javafx.scene package as import javafx.scene.Group; • Then create an object of it as Group var = new Group(); • Then add nodes to the object created • Then add the group object to the scene as a parent of the nodes
  • 26. No Layout import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.Group; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.stage.Stage; public class NoLayoutDemo extends Application { @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("I am a button"); CheckBox cb = new CheckBox("I am a check box"); cb.setLayoutX(185); cb.setLayoutY(230); Group root = new Group(); root.getChildren().add(btn); root.getChildren().add(cb); Scene scene = new Scene(root, 300, 250); scene.setOnMouseClicked(value -> { btn.setLayoutX(value.getX() - btn.getWidth() / 2); btn.setLayoutY(value.getY() - btn.getHeight() / 2); }); primaryStage.setTitle("No Layout Demo"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 27. JavaFX Color • Import it as import javafx.scene.paint.Color; • There are different ways to set the color of a node in javafx • Using the 147 predefined colors like Color.RED • Using rgb hexadecimal values • Using rgb decimal values • You can optionally provide an alpha value for transparency • 0 – fully transparent • 1 – fully opaque • The ff shows these three different ways to fill a rectangle Rectangle r = new Rectangle(60, 40); r.setFill(Color.LIGHTBLUE);//fully opaque r.setFill(Color.web("#ADD8E6")); r.setFill(Color.web("#ADD8E680"));//.5 opaque r.setFill(Color.rgb(173, 216, 230));//fully opaque r.setFill(Color.rgb(173, 216, 230,.5));//0.5 opaque
  • 28. JavaFX Text • A text is a shape with additional properties such as font, text alignment, text, and wrapping width • Import it from javafx.scene.text Text text = new Text("Hi there"); text.setFill(Color.RED); text.setFont(Font.font("Arial", 30)); text.setX(25); text.setY(200); • Font class is found in the javafx.scene.text
  • 29. CSS Styling • -fx prefix is used for the properties to clearly distinguish them from web ones and avoid any compatibility issues • JavaFX node classes have their selector counterparts, with naming convention being lowercase class name, with words separated by hyphens • For Button – the selector is button • For ListView – the selector is list-view • For the root of the scene – the selector is root • Etc • You are also allowed to use selectors based on custom style classes • Then you need to add the custom style class to the node you want to apply the style class • The third way is to use selectors based on Object ID • Use the setId(String value) method to set an id for the node • Then use this id in you css as a selector • The fourth way is to use the setStyle(String value) method in the javafx code.
  • 30. CSS Styling • Except the last option (using the setStyle() method) – the css needs to be specified in a separate css file (for example, style.css) • This file have to be stored in the build folder (with the bitecode files of the package that uses the css file) • Then this file needs to be loaded as follows • scene.getStyleSheets().add( getClass().getResource(“filename.css”).toExternalForm() ); • If the css file is on a remote computer over the internet, use the following to load it • scene.getStyleSheets().add(“http://www.someaddress.com/file.css”); • It is also possible to apply global stylesheets to the whole application • Application.setUserAgentStyleSheet() • JavaFX provides two default stylesheets, which are defined as constants • Application.setUserAgentStyleSheet(STYLESHEET_CASPIAN); //javafx 2 and before • Application.setUserAgentStyleSheet(STYLESHEET_MODENA);//default since JavaFX 8
  • 31. CSS Styling – Selectors by class name of the nodes .root { -fx-background-color: white; -fx-padding: 20px; } .label { -fx-background-color: black; -fx-text-fill: white; -fx-padding: 10px; } .button { -fx-background-color: blue; -fx-text-fill: red; } .list-view{ -fx-background-color: lightgrey; -fx-pref-width: 250px; } • Save it into, for example, style.css in the folder where the bytecode is stored • Then call scene.getStyleSheets.add() as described in the previous slide • The root selector is applied to the root node • The label selector is applied to every Label in the scene, • the button for every Button and • the list-view for every ListView node
  • 32. CSS Styling – Custome style class selector .make-it-bold{ -fx-font-weight:bold ; } .make-it-italic{ -fx-font-style:italic; } • Save it, for example, in style.css • Load this file as described previously • Then call the following method on the node you want to apply any of the custom class • .getStyleClass().add(“make-it-bold”);
  • 33. CSS Styling – Selector based on ID and using setStyle • Selector based on ID #big-bold-label { -fx-font-weight: bold; -fx-font-size: 20pt; } • Save the stylesheet file appropriately and load it as we did it previously • In this case, you need to set the id of the node you want to any one of the ids specified in the css • .setId(“big-bold-label) • You can directly specify the style for a node • On the node you want, call the setStyle method as follows • .setStyle( “-fx-background-color:black;” + “-fx-text-fill:white;”) • You can specify as many styles as you need once • The concatenation is for clarity – the string can be one big string
  • 34. Scene Builder and FXML • Instead of writing all the code for creating GUI nodes, JavaFX provides two important tools • FXML (FX Markup Language) • Similar to XML • Used to specify the nodes of the graph scene without writing java code • SceneBuilder • An application used to design the graph scene • By dragging and dropping UI elements into the graph scene without writing code • Then saving the designed scene graph into an FXML file (a file with extension of .fxml) • Download it and use it for free • After generating the fxml file, you can put it in your project appropriate directory • Then generate a controller class – use the IDE (that you use) to generate this control class • We will see how using the Net Beans IDE
  • 36. Scene Builder and FXML • Save it into the directory where your project is • For example, save it as example.fxml • On the IDE of your choice, generate the control class, in the Net Beans case • Right click on the example.fxml and click on Make Controller form the pop up menu • The controller is where some java code is written (for example, event handling, property binding, animation) • All the design is done for us by Scene Builder application using FXML • To add it to the scene • Parent pa = FXMLLoader.load(getClass().getResource(“example.fxml”); • Then add the pa object to a layout and to the scene
  • 37. Scene Builder and FXML <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.CheckBox?> <?import javafx.scene.control.Menu?> <?import javafx.scene.control.MenuBar?> <?import javafx.scene.control.MenuItem?> <?import javafx.scene.layout.AnchorPane?> <AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="- Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1"> <children> <Button layoutX="158.0" layoutY="117.0" mnemonicParsing="false" text="Button" /> <CheckBox layoutX="137.0" layoutY="211.0" mnemonicParsing="false" text="CheckBox" /> <MenuBar layoutX="14.0" layoutY="14.0"> <menus> <Menu mnemonicParsing="false" text="File"> <items> <MenuItem mnemonicParsing="false" text="Close" /> </items> </Menu> <Menu mnemonicParsing="false" text="Edit"> <items> <MenuItem mnemonicParsing="false" text="Delete" /> </items> </Menu> <Menu mnemonicParsing="false" text="Help"> <items> <MenuItem mnemonicParsing="false" text="About" /> </items> </Menu> </menus> </MenuBar> </children> </AnchorPane>
  • 38. Properties and Bindings • Property binding is a mechanism that enables to update one property when another property changes • A property is an attribute of a class that you can read or write • A property has a getter and setter that perform the read and write respectively • In JavaFX a property has a third method, in addition to getter and setter methods • This method returns an object implementing the Property interface • For example, a JavaFX text property has the following three methods • String getText() • void setText(String text) • Property<String> textProperty() • A listener can be attached to the Property object • Moreover, in JavaFX, to work with property binding • The property must be defined using the built-in classes provided by JavaFX • The javafx.beans.property package contains all the classes important for creating properties that automatically support property binding
  • 39. Properties and Bindings • The classes in javafx.beans.property For Primitive Types For Object Types StringProperty SimpleStringProperty IntegerProperty SimpleIntegerProperty FloatProperty SimpleFloatProperty LongProperty SimpleLongProperty DoubleProperty SimpleDoubleProperty BooleanProperty SimpleBooleanProperty ListProperty<E> SimpleListPropery<E> MapProperty<K,V> SimpleMapProperty<K,V> SetProperty<E> SimpleSetProperty<E> ObjectProperty<T> SimpleObjectProperty<T>
  • 40. Properties and Bindings • The need to create properties using these classes is to simply attach a listener that will be invoked whenever a property’s value is changed • There are two way • Using ChangeListener or • Using InvalidationListener • To demonstrate how consider the Greeting class import javafx.beans.property.StringProperty; import javafx.beans.property.SimpleStringProperty; public class Greeting { private StringProperty text = new SimpleStringProperty(""); public final StringProperty textProperty() { return text; } public final void setText(String text) { this.text.set(text); } public final String getText(){ return text.get(); } }
  • 41. Properties and Bindings • After creating an object of Greeting class • You can attach a listener using the InvalidationListener Greeting g = new Greeting(); g.setText(“Old Value”); g.textProperty().addListener(event->{ System.out.println(“The new value of greeting is: ’”+ g.getText()+”’”); }); g.setText(“A new value”) • You can also use the ChangeListener as follows g.setText(“Old Value”); g.textProperty().addListener((property, oldValue, newValue)->{ System.out.println(“The new value of greeting is: ’”+ newValue +”’”); }); g.setText(“A new value”) • In either case, whenever the value of the property is changed, an event is triggered that displays the new value on to the console • The main purpose of attaching a listener is for Binding • Binding – making a property to change its value whenever another property’s value is changed • For example, whenever the value of a TextField is changed, change the value of a Label or another node or another object and vice versa
  • 42. Properties and Bindings • The nodes of the JavaFX API has properties that are designed to support binding automatically • For example, the TextField has a textProperty, disableProperty, editableProperty, alignmentProperty, …… • The same is true for every other nodes of JavaFX • You can also define your own classes that support property binding using the classes found in the javafx.beans.property package • To make binding on the nodes call either the bind() or binBidirectional() method as follows • When the value of tf2 changes, the value of tf1 is replaced by the value of tf2 TextField tf1 = new TextField(); TextField tf2 = new TextField(); tf1.textProperty().bind(tf2.textProperty()); • The bind() method is used to force unidirectional binding (from tf2 to tf1 in the case of this example)
  • 43. Properties and Bindings • Two way binding can also be implemented as follows TextField tf1 = new TextField(); TextField tf2 = new TextField(); tf1.textProperty().bindBidirectional(tf2.textProperty()); • In the case of bindBidirectional() change is reflected in both direction (from tf1 to tf2 and also from tf2 to tf1) • Note: the nodes needs not be of same type • However, the properties must be compatible or you need to perform some computation before the binding occurs • For this purpose, there is a class called Bindings that contain static methods to perform some computation • tf1.textProperty().bind(Bindings.concat(“From TF2 - ”, tf2.textProperty()); • The Bindings class is found in the javafx.beans.binding package • You may also import it as static and use it as follows • import static javafx.beans.binding.Bindings.*; • tf1.textProperty().bind(concat(“From TF2 – “, tf2.textProperty()); • There are many methods available in the Bindings class • add, subtract, multiply, divide, max, min, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, equal, notEqual, equalIgnoreCase, notEqualIgnoreCase, ……
  • 44. Properties and Bindings – Example import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; public class Data { private DoubleProperty value = new SimpleDoubleProperty(0); public final DoubleProperty valueProperty(){ return value; } public final void setValue(double v){ value.set(v); } public final double getValue(){ return value.get(); } } import javafx.application.Application; import javafx.beans.binding.Bindings; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ProgressBar; import javafx.scene.control.ProgressIndicator; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class PropertyBindingDemo1 extends Application { public void start(Stage primaryStage) { Data data = new Data(); Button btn = new Button(); btn.setText("Increase"); ProgressBar pBar = new ProgressBar(); ProgressIndicator pIndicator = new ProgressIndicator();
  • 45. Properties and Bindings – Example btn.setOnAction(event -> { if (data.getValue() < 100) { data.setValue(data.getValue() + 5); } }); Button btn1 = new Button("Decrease"); btn1.setOnAction(event -> { if (data.getValue() > 0) { data.setValue(data.getValue() - 5); } }); Bar.progressProperty().bind(Bindings.divide(data.valueProperty(), 100)); pIndicator.progressProperty().bind(pBar.progressProperty()); GridPane root = new GridPane(); root.add(pBar, 0, 0); root.add(pIndicator, 1, 0); root.add(btn, 0, 1); root.add(btn1,1,1); Scene scene = new Scene(root); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 46. Properties and Bindings – Centering a node when the scene resizes • Using the following will make the rectangle at center at the beginning; but when the window resizes, the rectangle will no longer be at the center rect.setX(scene.getWidth()/2 - rect.getWidth()/2); rect.setY(scene.getHeight()/2 - rect.getHeight()/2); • The following program, using property binding, make the rectangle at the center what ever the size of the scene is import javafx.application.Application; import javafx.beans.binding.Bindings; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class PropertyBindingDemo2 extends Application { public void start(Stage primaryStage) { Rectangle rect = new Rectangle(100,100,Color.SKYBLUE); Group root = new Group(); root.getChildren().add(rect); Scene scene = new Scene(root, 300, 250); rect.xProperty().bind(Bindings.subtract( Bindings.divide(scene.widthProperty(), 2), Bindings.divide(rect.widthProperty(), 2)) ); rect.yProperty().bind(Bindings.subtract( Bindings.divide(scene.heightProperty(), 2), Bindings.divide(rect.heightProperty(), 2)) ); primaryStage.setTitle("Centering upon resize"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 47. Graphics and Animation • JavaFX provides set of classes that enable us to work with graphics • The javafx.scene.shape package provides classes to work with shapes • All classes in this package are subclasses of the class Shape (javafx.scene.shape.Shape) – which in turn is a subclass of the Node class (javafx.scene.Node) • Some of the common classes in this package are • Line, Rectangle, Arc, Circle, Ellipse, Path, Polygon, Polyline, etc • JavaFX also provides a library for making animations • The package containing the classes for animation is javafx.animation • There are predefined animation classes to use such as • FadeTransition, PathTransition, ScaleTransition, TranslateTransition, etc. • Or, you can do things by yourself using the classes • KeyValue, KeyFrame, TimeLine, etc.
  • 48. Graphics and Animation – Drawing Line • The class for drawing line is javafx.scene.shape.Line • There are two ways • Creating a line object by specifying the start and end coordinates of the line as follows – a line from (200, 30) to (100, 50) Line line = new Line(200, 30 , 100, 50); • The second way is to create an object without the points and use the setter methods to set the point Line line = new Line(); line.setStartX(200); line.setStartY(30); line.setEndX(100); line.setEndY(50); • By default, • Line nodes have a stroke width of 1.0 and a stroke color of black (Color.BLACK) • Then, use the properties inherited from the Shape class to create different kinds of lines
  • 49. Graphics and Animation – Drawing Line • The Shape class provides the following properties • fill – a color to fill inside a shape • strokeDashOffset – the offset (distance) into the dashed pattern (between repeated pattens) • strokeLineCap – the cap style on the end of a line or path • strokeLineJoin – decoration when lines meet • stroke – a color of the shape’s line stroke • strokeType – where to draw the stroke around the boundary of a Shape node – center, outside or inside • strokeWidth – a stroke lines width
  • 50. Graphics and Animation – Drawing Line public void start(Stage primaryStage) { Line line = new Line(200,30,100,30); line.setStroke(Color.RED); line.getStrokeDashArray().addAll(15d); line.setStrokeDashOffset(0); line.setStrokeWidth(3); StackPane root = new StackPane(); root.getChildren().add(line); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Line Demo"); primaryStage.setScene(scene); primaryStage.show(); }
  • 51. Graphics and Animation – Drawing Rectangle • The javafx.scene.shape.Rectangle inherits the same methods from the javafx.scene.shape.Shape class • To draw a rectangle, the constructors are • Rectangle() • Rectangle(width, height) • Rectangle(width, height, fillColor) • Rectangle(xLocation, yLocation, width, height) • Use any of the constructor and then modify the properties as you like; some of the set methods are • setX(), setY(), setWidth(), setHeight(), setFill(), setArcWidth(), setArkHeight() • The last two are used to create a round rectangle Rectangle roundRect = new Rectangle(); roundRect.setX(50); roundRect.setY(50); roundRect.setWidth(100); roundRect.setHeight(130); roundRect.setArcWidth(10); roundRect.setArcHeight(40); • Shapes such as Ellipse, Circle, Polygon can be easily drawn in a similar fashion
  • 52. Graphics and Animation – Complex Shapes • CubicCurve • To draw graphics which looks as a sign wave • Use the following constructor CubicCurve cubic = new CubicCurve(startX, startY, controlx1, controly1, controlx2, controly2, endx, endy) • QuadCurve – similar to the CubicCurve but with only one control point • Use the following constructor • QuadCurve quadC = new QuadCurve(startX, startY, controlX, controlY, endX, endY)
  • 53. Graphics and Animation – Complex Shapes public void start(Stage primaryStage) { Group g = new Group(); CubicCurve cubic = new CubicCurve(50, 50, 75, 0, 125, 100, 150, 50); cubic.setFill(Color.WHITE); cubic.setStroke(Color.BLACK); cubic.setStrokeWidth(3); QuadCurve quad = new QuadCurve(50, 200, 75, 50, 100, 200); quad.setFill(Color.WHITE); quad.setStroke(Color.BLACK); quad.setStrokeWidth(3); Scene scene = new Scene(g, 300, 250); g.getChildren().add(cubic); g.getChildren().add(quad); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); }
  • 54. Graphics and Animation – Complex Shapes • Path • Is a class used to draw any shape you want by combining points called path elements • These path elements are a subclass of the class PathElement • The following are the path elements • LineTo • MoveTo • QuadCurveTo • CubicCurveTo • The path elements are not subclass of the Node class – as a result they cannot be child nodes in the scene graph • Instead, they are added to the Path object in the order we need the shape to draw.
  • 55. Graphics and Animation – Complex Shapes public void start(Stage primaryStage) { Path p = new Path(); MoveTo mt = new MoveTo(50, 50); LineTo lt = new LineTo(150, 50); LineTo lt1 = new LineTo(100, 125); LineTo lt3 = new LineTo(50, 50); p.getElements().addAll(mt, lt, lt1, lt3); AnchorPane root = new AnchorPane(); root.getChildren().add(p); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); }
  • 56. Graphics and Animation - Canvas • JavaFX has a complete set of controls for use and allows developers to style their applications using CSS • Among all the controls provided by JavaFX, we have the powerful Canvas – higher performance graphics • Used to create visually impressive graphics applications that make use of JavaFX hardware acceleration graphics • Imagine that • You were given the task of creating a JavaFX game or • You have to build a simulation or • You have to build some other kind of application that requires continuous update of the screen • For such cases, the Canvas is used instead of the standard UI control APIs • it doesn’t mean that you cannot use the standard control UI to do so • The package containing the Canvas class is javafx.scene.canvas • The Canvas class, like all other JavaFX nodes, it is a subclass of Node
  • 57. Graphics and Animation - Canvas • To work with Canvas • Create an object of the canvas class – Canvas canvas = new Canvas(); • Set the width and height of the canvas – canvas.setWidth(400); • Get the 2D graphics context of the canvas – GraphicsContext graphicsContext2D = canvas.getGraphicsContext2D(); • Then using the methods of the GraphicsContext object, you can draw anything you want • Add the canvas object to one of the layout pane • Add the layout pane object to the scene object • Add the scene object to the stage • Some of the methods of the GraphicsContext object are • setFill() • setStroke() • fillRect() • fillOval() • fillRoundRect() • fillText() • setLineWidth() • setTextAlign() • setFont() • Etc • Using these and other methods you can draw graphics on the canvas
  • 58. Graphics and Animation - Canvas public void start(Stage primaryStage) { Canvas c = new Canvas(); c.setWidth(300); c.setHeight(300); GraphicsContext gc = c.getGraphicsContext2D(); gc.setFill(Color.RED); gc.fillRect(20, 20, 60, 90); gc.setFill(Color.GREY); gc.setStroke(Color.RED); gc.setLineWidth(3); gc.strokeOval(20, 150, 80, 50); gc.fillOval(20, 210, 80, 50); gc.strokeOval(20, 210, 80, 50); StackPane root = new StackPane(); root.getChildren().add(c); Scene scene = new Scene(root); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); }
  • 59. Graphics and Animation – Animation • The javafx.animation package provides classes to work with animation • Allows us to assemble timed events that can interpolate over property-based values (Property) in order to produce animated effects • For example, to produce a fade-out effect, you would target a node’s opacity property to interpolate its value starting from 1 (fully opaque) to 0 (transparent) over a period of time • KeyValue class • Defines the start and end values of a property to interpolate between • The KeyValue object can be of type Interpolator.EASE_IN, or Interpolator.EASE_OUT, or Interpolator.EASE_BOTH – specify any of these in the constructor • The KeyValue class can be used as follows Rectangle rectangle = new Rectangle(0, 0, 50, 50); KeyValue keyValue = new KeyValue(rectangle.opacityProperty(), 0); • KeyFrame class • When an animation (Timeline) occurs, each timed event is called a keyframe (a KeyFrame object) • A KeyFrame object is responsible for interpolating key values (KeyValue objects) over a period of time (javafx.util.Duration)
  • 60. Graphics and Animation – Animation • KeyFrame class (continued) • Is used with KeyValue objects such as Rectangle rectangle = new Rectangle(0, 0, 50, 50); KeyValue xValue = new KeyValue(rectangle.xProperty(), 100); KeyValue yValue = new KeyValue(rectangle.yProperty(), 100); KeyFrame keyFrame = new KeyFrame(Duration.millis(1000), xValue, yValue); • The previous code defines a keyframe to move a rectangle’s upper-left corner (0, 0) to point (100, 100) in one second or 1000 milliseconds • Timeline class • A Timeline is one animation sequence consisting of many KeyFrame objects • Each KeyFrame object is run sequentially • The Timeline class has standard attributes such as its cycle count and auto-reverse that you can set; these attributes are inherited form javafx.animation.Animation class • The cycle count is the number of times you want the timeline to play the animation • The auto-reverse property is a Boolean flag to indicate that the animation can play the timeline backward (the keyframes in reverse order) • By default, the cycle count is set to 1, and auto-reverse is set to false
  • 61. Graphics and Animation – Animation • Timeline class (continued) • It is used as follows Timeline timeline = new Timeline(); //KeyFrame objects can be passed here with the constructor timeline.setCycleCount(Timeline.INDEFINITE);//or you can specify how many times to repeate timeline.setAutoReverse(true); timeline.getKeyFrames().addAll(keyFrame1, keyFrame2); //this also adds KeyFrame objects timeline.play(); • The following example demonstrates the use of KeyValue, KeyFrame, TimeLine classes
  • 62. Graphics and Animation – Animation public class AnimationDemo extends Application { public void start(Stage primaryStage) { Group root = new Group(); Rectangle rectangle = new Rectangle(0, 0, 50, 50); Rectangle rectangle1 = new Rectangle(80,0,50,50); rectangle1.setFill(Color.BLUE); root.getChildren().addAll(rectangle, rectangle1); KeyValue xValue = new KeyValue(rectangle.xProperty(), 100); KeyValue yValue = new KeyValue(rectangle.yProperty(), 100); KeyFrame keyFrame = new KeyFrame(Duration.millis(1000), xValue, yValue); KeyValue keyValue1 = new KeyValue(rectangle1.opacityProperty(), 0); KeyFrame keyFrame1 = new KeyFrame(Duration.millis(1000), keyValue1); Timeline timeline = new Timeline(); timeline.setCycleCount(Timeline.INDEFINITE); timeline.setAutoReverse(true); timeline.getKeyFrames().addAll(keyFrame, keyFrame1); timeline.play(); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 63. Graphics and Animation – Animation • For common animation effects, javafx.animation provides predefined classes that can be used without coding low-level using Key values, key frames, timeline – the following are some of these classes • FadeTransition – fade animation by changing the opacity of the node • PathTransition – for translating a node along a predefined path • ScaleTransition – for increasing or decreasing the size of the node • TranslateTransition – for moving a node • FillTransition – animation by changing the fill color of a node • RotateTransition – rotating a node in the scene graph • ParallelTransition – set of animations in parallel • SequentialTransition – set of animations in sequential order • The following program demonstrates how to use these predefined classes
  • 64. Graphics and Animation – Animation public class AnimationDemo1 extends Application { @Override public void start(Stage primaryStage) { Group root = new Group(); Ellipse e = new Ellipse(300, 50, 100, 50); FillTransition ft = new FillTransition(Duration.millis(3000), e, Color.RED, Color.BLUE); ft.setCycleCount(2); ft.setAutoReverse(true); TranslateTransition tt = new TranslateTransition(Duration.millis(5000),e); tt.setToX(-100); tt.setToY(300); ParallelTransition pt = new ParallelTransition(ft, tt); pt.play(); //to make it sequential comment the ParallelTransition (the //above two statements) and uncomment the following two //statements //SequentialTransition st = new SequentialTransition(ft, tt); //st.play(); Scene scene = new Scene(root, 400, 400); root.getChildren().addAll(e); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
  • 65. Graphics and Animation – Animation