SlideShare a Scribd company logo
1 of 49
Download to read offline
JavaFX fundamentals

Tecniche di Programmazione – A.A. 2012/2013
Summary
1.   Application structure
2.   The Scene Graph
3.   Events
4.   Properties and Bindings




 2                             Tecniche di programmazione   A.A. 2012/2013
Application structure

      Introduction to JavaFX
4   Tecniche di programmazione   A.A. 2012/2013
Separation of concerns




5                Tecniche di programmazione   A.A. 2012/2013
General class diagram
                                .launch()
                                creates
           Application                               Stage

                                                                         .setScene
     extends                    .start()
                                creates
                                                     Scene
             MyApp                                                                Root node
                                                          children                (at constructor)

                         creates
                                                     Node
                         adds




                     Parent                       (leaf) Node                     (root) Node
children


 6                                          Tecniche di programmazione   A.A. 2012/2013
General rules
       A JavaFX application extends
        javafx.application.Application
       The main() method should call Application.launch()
       The start() method is the main entry point for all JavaFX
        applications
           Called with a Stage connected to the Operating System’s
            window
       The content of the scene is represented as a hierarchical
        scene graph of nodes
           Stage is the top-level JavaFX container
           Scene is the container for all content

    7                                  Tecniche di programmazione   A.A. 2012/2013
Minimal example
public class HelloWorld extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");

            Button btn = new Button();
            btn.setText("Say 'Hello World'");

            StackPane root = new StackPane();

            root.getChildren().add(btn);

            primaryStage.setScene(new Scene(root, 300, 250));
            primaryStage.show();
    }
}

        8                                  Tecniche di programmazione   A.A. 2012/2013
Stage vs Scene

javafx.stage.Stage                        javafx.scene.Scene

       The JavaFX Stage class is the        the container for all content
        top level JavaFX container.           in a scene graph
       The primary Stage is                 The application must specify
        constructed by the platform.          the root Node for the scene
       Additional Stage objects may          graph
        be constructed by the                Root may be Group (clips),
        application.                          Region, Control (resizes)
       A stage can optionally have          If no initial size is specified, it
        an owner Window.                      will automatically compute it


    9                               Tecniche di programmazione   A.A. 2012/2013
Nodes
    The Scene is populated with a tree of Nodes
        Layout components
        UI Controls
        Charts
        Shapes
    Nodes have Properties
        Visual (size, position, z-order, color, ...)
        Contents (text, value, data sets, ...)
    Nodes generate Events
        UI events
    Nodes can be styled with CSS

    10                                 Tecniche di programmazione   A.A. 2012/2013
Events
    FX Event (javafx.event.Event):
        Event Source => a Node
        Event Target
        Event Type
    Usually generated after some user action
    ActionEvent, TreeModificationEvent, InputEvent, ListView.E
     ditEvent, MediaErrorEvent, TableColumn.CellEditEvent,Tre
     eItem.TreeModificationEvent, TreeView.EditEvent, WebEve
     nt, WindowEvent, WorkerStateEvent
    You can define event handlers in your application


    11                            Tecniche di programmazione   A.A. 2012/2013
Properties
    Extension of the Java Beans convention
        May be used also outside JavaFX
    Encapsulate properties of an object
        Different types (string, number, object, collection, ...)
        Set/Get
        Observe changes
        Supports lazy evaluation
    Each Node has a
     large set of Properties



    12                                Tecniche di programmazione   A.A. 2012/2013
Bindings
    Automatically connect («bind») one Property to another
     Property
        Whenever the source property changes, the bound one is
         automatically updated
        Multiple bindings are supported
        Lazy evaluation is supported
        Bindings may also involve computations (arithmetic operators,
         if-then-else, string concatenation, ...) that are automatically
         evaluated
    May be used to automate UI
    May be used to connect the Model with the View

    13                             Tecniche di programmazione   A.A. 2012/2013
The Scene graph

 Introduction to JavaFX
Nodes
    Root node: top level container
    Intermediate nodes:
        Containers
        Layout managers
        UI Composite controls
    Leaf (terminal) nodes:
        Shapes
        UI Controls
    Organized as a Hierarchical tree



    15                           Tecniche di programmazione   A.A. 2012/2013
ChoiceBox
                                                                   ColorPicker
                                             ComboBoxBase                          Button
                                                                   ComboBox



Nodes family
                                                                                  CheckBox
                                                                   ButtonBase
                                                                                 MenuButton
                                                                      Cell
                                                 Labeled                         ToggleButton
                                                                      Label
                                                 ListView
                                 Control                           TitledPane


                                  Group
                                                MenuBar
                                                                                                                 Focus on
                                                  Slider                                                          Panes
                                                 TabPane                                                           and
                                             TextInputControl
                                                                    TextArea
                                                                                                                 Controls
                                                                    TextField
                      Parent
                                                 ToolBar
                                                                   AnchorPane
                                                TreeView
                                                                   BorderPane
                                                   Axis
                                                                    FlowPane
                                  Region          Chart
                                                                    GridPane
                                 WebView          Pane

 javafx.scene.Node
                                   Arc
                                                                     HBox
                                                                                                                 JavaDoc
                                                                   StackPane                                      is your
                                                                                                                   friend
                                  Circle
                                                                    TilePane
                                   Line
                      Shape                                           VBox
                                 Polygon
                      Canvas
                                 Rectangle
                     Imageview
16                                 Text                         Tecniche di programmazione      A.A. 2012/2013
Exploring Controls and Examples
    JavaFX Ensemble demo
     application
    Download from Oracle
     site: JavaFX Demos and
     Samples Downloads
    Run Ensemble.jnlp




    17                        Tecniche di programmazione   A.A. 2012/2013
UI Form Controls
    Controls may be
     combined to construct
     «Forms»
    Control Nodes have a
     value property
        May be linked to application
         code
    Control Nodes generate
     UI Events
        Button: ActionEvent
        Text: ActionEvent,
         KeyTyped, KeyPressed,
         MouseClicked, ...

    18                             Tecniche di programmazione   A.A. 2012/2013
19   Tecniche di programmazione   A.A. 2012/2013
Layout Class Hierarchy
    Group:
        Doesn’t perform any positioning of children.
        To statically assemble a collection of nodes in fixed positions
        To apply an effect or transform to that collection.
    Region:
        base class for all general purpose layout panes
        resizable and stylable via CSS
        Supports dynamic layout by sizing and positioning children
    Control:
        the base class for all skinnable controls
        resizable and subclasses are all stylable via CSS
        Controls delegate layout to their skins (which are Regions)
        Each layout Control subclass provides API for adding content in the
         appropriate place within its skin
            you do not add children to a control directly.

    20                                     Tecniche di programmazione   A.A. 2012/2013
21   Tecniche di programmazione   A.A. 2012/2013
22   Tecniche di programmazione   A.A. 2012/2013
23   Tecniche di programmazione   A.A. 2012/2013
24   Tecniche di programmazione   A.A. 2012/2013
25   Tecniche di programmazione   A.A. 2012/2013
26   Tecniche di programmazione   A.A. 2012/2013
27   Tecniche di programmazione   A.A. 2012/2013
28   Tecniche di programmazione   A.A. 2012/2013
Creating the Scene Graph
    The Java way
        Create Control Nodes
        Set properties to new nodes
        Add new nodes to parent node
        With Constructors and/or with Builders
    The FXML way
        Create a FXML file
        Define Nodes and Properties in FXML
        Load the FXML
        (Optionally, add new nodes/properties the Java way)



    29                             Tecniche di programmazione   A.A. 2012/2013
Example: one text input field

TextField text = new TextField("Text");                           Constructors
text.setMaxSize(140, 20);
root.getChildren().add(text);




TextField text = TextFieldBuilder().create()
                      .maxHeight(20).maxWidth(140)
                      .text("Text")
                      .build() ;
                                                                  Builders
root.getChildren().add(text);

  30                            Tecniche di programmazione   A.A. 2012/2013
public class HelloDevoxx extends Application {
       public static void main(String[] args)
       {
               launch(args);
       }

         @Override
         public void start(Stage primaryStage)
         {
                primaryStage.setTitle("Hello Devoxx");
                Group root = new Group();
                Scene scene = new Scene(root, 400, 250,
                        Color.ALICEBLUE);
                Text text = new Text();
                text.setX(105);
                text.setY(120);
                text.setFont(new Font(30));
                text.setText("Hello Devoxx");
                root.getChildren().add(text);
                primaryStage.setScene(scene);
                primaryStage.show();
         }
}
    31                         Tecniche di programmazione   A.A. 2012/2013
public void start(Stage primaryStage)
{
       primaryStage.setTitle("Hello Devoxx");
       primaryStage.setScene(SceneBuilder.create()
                      .width(400).height(250).fill(Color.ALICEBLUE)
                      .root(GroupBuilder.create().children(
                                     TextBuilder.create()
                                     .x(105).y(120)
                                     .text("Hello Devoxx")
                                     .font(new Font(30)).build()
                                     ).build()
                                     ).build());

         primaryStage.show();
}




    32                          Tecniche di programmazione   A.A. 2012/2013
The FXML way...
    XML-based format
    Nested tree of XML Elements, corresponding to Nodes
    XML Attributes corresponding to (initial) properties of
     nodes

    JavaFX Scene Builder is a GUI for creating FXML files

    The FXMLLoader class reads a FXML file and creates all
     the Nodes



    33                        Tecniche di programmazione   A.A. 2012/2013
Example




34        Tecniche di programmazione   A.A. 2012/2013
JavaFX Scene Builder




35              Tecniche di programmazione   A.A. 2012/2013
FXMLLoader

     @Override
     public void start(Stage stage) throws Exception {
         Parent root = FXMLLoader.load(
                  getClass().getResource("fxml_example.fxml"));

         stage.setTitle("FXML Welcome");
         stage.setScene(new Scene(root, 300, 275));
         stage.show();
     }




36                             Tecniche di programmazione   A.A. 2012/2013
Linking FXML and Java
    FXML element may have an associated attribute fx:id
    Nodes may be later retrieved by
        public Node lookup(java.lang.String selector)
        Finds a node with a specified ID in the current sub-tree
        Example:
            scene.lookup("#myId");
    Node references can also be «injected» using the
     @FXML annotation (see later)




    37                           Tecniche di programmazione   A.A. 2012/2013
Events

Introduction to JavaFX
Interacting with Nodes
    In JavaFX applications, events are notifications that
     something has happened.
        An event represents an occurrence of something of interest to
         the application
        As a user clicks a button, presses a key, moves a mouse, or
         performs other actions, events are dispatched.
    Registered event filters and event handlers within the
     application
        receive the event and
        provide a response.



    39                            Tecniche di programmazione   A.A. 2012/2013
What is an event?




40                  Tecniche di programmazione   A.A. 2012/2013
Event propagation
    Events are generated on the source node
    Events propagated in the scene graph hierarchy («dispatch
     chain»), in two phases
        Dispatching: downwards, from root to source node
            Processes Event Filters registered in the nodes
        Bubbling: upwards, from source node to root
            Processes Event Handlers registered in the nodes
    If you want an application to be notified
     when an event occurs, register a filter
     or a handler for the event
    Handlers may “consume” the event

    41                                   Tecniche di programmazione   A.A. 2012/2013
Event Handlers
    Implements the EventHandler interface
    Executed during the event bubbling phase.
    If does not consume the event, it is propagated to the
     parent.
    A node can register more than one handler.
    Handlers for a specific event type are executed before
     handlers for generic event types.
        For example, a handler for the KeyEvent.KEY_TYPED event is
         called before the handler for the InputEvent.ANY event.
    To consume an event, call the consume() method


    42                           Tecniche di programmazione   A.A. 2012/2013
Registering Event Handlers
    setOnEvent-type(
     EventHandler<? super event-class> value )
        Event-Type
            The type of event that the handler processes (e.g. setOnKeyTyped,
             setOnMouseClicked, ...)
        Event-class
            The class that defines the event type (e.g., KeyEvent , MouseEvent, ...)
        Value
            The event handler for event-class (or for one of its super classes)
            Must implement: public void handle(ActionEvent event)
            May be a regular class or an anonymous inline class



    43                                    Tecniche di programmazione   A.A. 2012/2013
Example
class ButtonActionHandler implements                         Event Handler
javafx.event.EventHandler<ActionEvent> {

     public ButtonActionHandler (/*params*/) {
         // constructor - if needed
     }

     @Override
     public void handle(ActionEvent event) {
         Button b = (Button)event.getSource() ;
         //...do something
         String buttonText = b.getText() ;
         // ...
     }                                                                Registration
}
                   Button btn = new Button() ;

                   btn.setOnAction(new ButtonActionHandler()) ;
    44                          Tecniche di programmazione    A.A. 2012/2013
Example (inline definition)

                                               Registration &
                                               Anonymous event handler
     btn.setOnAction(new EventHandler<ActionEvent>() {

                   public void handle(ActionEvent event) {
                       System.out.println("Hello World");
                   }

             });




45                            Tecniche di programmazione   A.A. 2012/2013
To be continued...
    Properties and Bindings

             Introduction to JavaFX
Resources

Introduction to JavaFX
Resources
    API
        http://docs.oracle.com/javafx/2/api/index.html
    Slides/Tips
        http://www.slideshare.net/steveonjava/java-fx-20-a-developers-guide
        http://refcardz.dzone.com/refcardz/getting-started-javafx
    Tutorials/Articles
        http://docs.oracle.com/javafx/2/events/jfxpub-events.htm
        http://amyfowlersblog.wordpress.com/2011/06/02/javafx2-0-layout-a-
         class-tour/
    Examples (Downloads)
        JavaFX Demos and Samples, at
         http://www.oracle.com/technetwork/java/javase/downloads/jdk7-
         downloads-1880260.html


    48                                Tecniche di programmazione   A.A. 2012/2013
Licenza d’uso
    Queste diapositive sono distribuite con licenza Creative Commons
     “Attribuzione - Non commerciale - Condividi allo stesso modo (CC
     BY-NC-SA)”
    Sei libero:
        di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico,
         rappresentare, eseguire e recitare quest'opera
        di modificare quest'opera
    Alle seguenti condizioni:
        Attribuzione — Devi attribuire la paternità dell'opera agli autori
         originali e in modo tale da non suggerire che essi avallino te o il modo in
         cui tu usi l'opera.
        Non commerciale — Non puoi usare quest'opera per fini
         commerciali.
        Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se
         la usi per crearne un'altra, puoi distribuire l'opera risultante solo con una
         licenza identica o equivalente a questa.
    http://creativecommons.org/licenses/by-nc-sa/3.0/
    49                                   Tecniche di programmazione   A.A. 2012/2013

More Related Content

What's hot

Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Creating a frame within an applet
Creating a frame within an appletCreating a frame within an applet
Creating a frame within an appletmyrajendra
 
L11 array list
L11 array listL11 array list
L11 array listteach4uin
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java Ravi_Kant_Sahu
 

What's hot (20)

Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Creating a frame within an applet
Creating a frame within an appletCreating a frame within an applet
Creating a frame within an applet
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java Swing
Java SwingJava Swing
Java Swing
 
07 java collection
07 java collection07 java collection
07 java collection
 
L11 array list
L11 array listL11 array list
L11 array list
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java Streams
Java StreamsJava Streams
Java Streams
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
 

Viewers also liked

Introduction to JavaFX
Introduction to JavaFXIntroduction to JavaFX
Introduction to JavaFXFulvio Corno
 
JavaFX: A nova biblioteca gráfica da plataforma Java
JavaFX: A nova biblioteca gráfica da plataforma JavaJavaFX: A nova biblioteca gráfica da plataforma Java
JavaFX: A nova biblioteca gráfica da plataforma JavajesuinoPower
 
Desenvolvimento rápido de aplicações com JEE e JavaFX
Desenvolvimento rápido de aplicações com JEE e JavaFXDesenvolvimento rápido de aplicações com JEE e JavaFX
Desenvolvimento rápido de aplicações com JEE e JavaFXjesuinoPower
 
Boas práticas na criação de aplicações sérias com JavaFX - TDC 2014 SP
Boas práticas na criação de aplicações sérias com JavaFX - TDC 2014 SPBoas práticas na criação de aplicações sérias com JavaFX - TDC 2014 SP
Boas práticas na criação de aplicações sérias com JavaFX - TDC 2014 SPjesuinoPower
 
JavaFX 8, Collections e Lambdas
JavaFX 8, Collections e LambdasJavaFX 8, Collections e Lambdas
JavaFX 8, Collections e LambdasjesuinoPower
 
JavaFX: Desktop para desenvolvedores WEB
JavaFX: Desktop para desenvolvedores WEBJavaFX: Desktop para desenvolvedores WEB
JavaFX: Desktop para desenvolvedores WEBjesuinoPower
 

Viewers also liked (6)

Introduction to JavaFX
Introduction to JavaFXIntroduction to JavaFX
Introduction to JavaFX
 
JavaFX: A nova biblioteca gráfica da plataforma Java
JavaFX: A nova biblioteca gráfica da plataforma JavaJavaFX: A nova biblioteca gráfica da plataforma Java
JavaFX: A nova biblioteca gráfica da plataforma Java
 
Desenvolvimento rápido de aplicações com JEE e JavaFX
Desenvolvimento rápido de aplicações com JEE e JavaFXDesenvolvimento rápido de aplicações com JEE e JavaFX
Desenvolvimento rápido de aplicações com JEE e JavaFX
 
Boas práticas na criação de aplicações sérias com JavaFX - TDC 2014 SP
Boas práticas na criação de aplicações sérias com JavaFX - TDC 2014 SPBoas práticas na criação de aplicações sérias com JavaFX - TDC 2014 SP
Boas práticas na criação de aplicações sérias com JavaFX - TDC 2014 SP
 
JavaFX 8, Collections e Lambdas
JavaFX 8, Collections e LambdasJavaFX 8, Collections e Lambdas
JavaFX 8, Collections e Lambdas
 
JavaFX: Desktop para desenvolvedores WEB
JavaFX: Desktop para desenvolvedores WEBJavaFX: Desktop para desenvolvedores WEB
JavaFX: Desktop para desenvolvedores WEB
 

Similar to JavaFX fundamentals

Programming with JavaFX
Programming with JavaFXProgramming with JavaFX
Programming with JavaFXFulvio Corno
 
Programming with JavaFX
Programming with JavaFXProgramming with JavaFX
Programming with JavaFXFulvio Corno
 
Java session10
Java session10Java session10
Java session10Niit Care
 
Java AWT and Java FX
Java AWT and Java FXJava AWT and Java FX
Java AWT and Java FXpratikkadam78
 
Tutorial on J2EE versus .NET for .NET Programmers
Tutorial on J2EE versus .NET for .NET Programmers Tutorial on J2EE versus .NET for .NET Programmers
Tutorial on J2EE versus .NET for .NET Programmers David Freitas
 
L0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitL0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitTonny Madsen
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfSakkaravarthiS1
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
Netbeans-platform ref_card
  Netbeans-platform ref_card  Netbeans-platform ref_card
Netbeans-platform ref_cardrajankadam
 
Netbeans-platform ref_card
  Netbeans-platform ref_card  Netbeans-platform ref_card
Netbeans-platform ref_cardrajankadam
 
Building Accessible Apps using NET MAUI.pdf
Building Accessible Apps using NET MAUI.pdfBuilding Accessible Apps using NET MAUI.pdf
Building Accessible Apps using NET MAUI.pdfSivarajAmbat1
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.pptTabassumMaktum
 
Spring as a Cloud Platform (Developer Summit 2011 17-C-5)
Spring as a Cloud Platform (Developer Summit 2011 17-C-5)Spring as a Cloud Platform (Developer Summit 2011 17-C-5)
Spring as a Cloud Platform (Developer Summit 2011 17-C-5)Kazuyuki Kawamura
 

Similar to JavaFX fundamentals (20)

JavaYDL12
JavaYDL12JavaYDL12
JavaYDL12
 
12slide
12slide12slide
12slide
 
Programming with JavaFX
Programming with JavaFXProgramming with JavaFX
Programming with JavaFX
 
Programming with JavaFX
Programming with JavaFXProgramming with JavaFX
Programming with JavaFX
 
Java session10
Java session10Java session10
Java session10
 
Java AWT and Java FX
Java AWT and Java FXJava AWT and Java FX
Java AWT and Java FX
 
Tutorial on J2EE versus .NET for .NET Programmers
Tutorial on J2EE versus .NET for .NET Programmers Tutorial on J2EE versus .NET for .NET Programmers
Tutorial on J2EE versus .NET for .NET Programmers
 
L0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitL0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget Toolkit
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
Context at design
Context at designContext at design
Context at design
 
Windows phone and azure
Windows phone and azureWindows phone and azure
Windows phone and azure
 
Netbeans-platform ref_card
  Netbeans-platform ref_card  Netbeans-platform ref_card
Netbeans-platform ref_card
 
Netbeans-platform ref_card
  Netbeans-platform ref_card  Netbeans-platform ref_card
Netbeans-platform ref_card
 
Building Accessible Apps using NET MAUI.pdf
Building Accessible Apps using NET MAUI.pdfBuilding Accessible Apps using NET MAUI.pdf
Building Accessible Apps using NET MAUI.pdf
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.ppt
 
Spring as a Cloud Platform (Developer Summit 2011 17-C-5)
Spring as a Cloud Platform (Developer Summit 2011 17-C-5)Spring as a Cloud Platform (Developer Summit 2011 17-C-5)
Spring as a Cloud Platform (Developer Summit 2011 17-C-5)
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 

Recently uploaded (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 

JavaFX fundamentals

  • 1. JavaFX fundamentals Tecniche di Programmazione – A.A. 2012/2013
  • 2. Summary 1. Application structure 2. The Scene Graph 3. Events 4. Properties and Bindings 2 Tecniche di programmazione A.A. 2012/2013
  • 3. Application structure Introduction to JavaFX
  • 4. 4 Tecniche di programmazione A.A. 2012/2013
  • 5. Separation of concerns 5 Tecniche di programmazione A.A. 2012/2013
  • 6. General class diagram .launch() creates Application Stage .setScene extends .start() creates Scene MyApp Root node children (at constructor) creates Node adds Parent (leaf) Node (root) Node children 6 Tecniche di programmazione A.A. 2012/2013
  • 7. General rules  A JavaFX application extends javafx.application.Application  The main() method should call Application.launch()  The start() method is the main entry point for all JavaFX applications  Called with a Stage connected to the Operating System’s window  The content of the scene is represented as a hierarchical scene graph of nodes  Stage is the top-level JavaFX container  Scene is the container for all content 7 Tecniche di programmazione A.A. 2012/2013
  • 8. Minimal example public class HelloWorld extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Hello World!"); Button btn = new Button(); btn.setText("Say 'Hello World'"); StackPane root = new StackPane(); root.getChildren().add(btn); primaryStage.setScene(new Scene(root, 300, 250)); primaryStage.show(); } } 8 Tecniche di programmazione A.A. 2012/2013
  • 9. Stage vs Scene javafx.stage.Stage javafx.scene.Scene  The JavaFX Stage class is the  the container for all content top level JavaFX container. in a scene graph  The primary Stage is  The application must specify constructed by the platform. the root Node for the scene  Additional Stage objects may graph be constructed by the  Root may be Group (clips), application. Region, Control (resizes)  A stage can optionally have  If no initial size is specified, it an owner Window. will automatically compute it 9 Tecniche di programmazione A.A. 2012/2013
  • 10. Nodes  The Scene is populated with a tree of Nodes  Layout components  UI Controls  Charts  Shapes  Nodes have Properties  Visual (size, position, z-order, color, ...)  Contents (text, value, data sets, ...)  Nodes generate Events  UI events  Nodes can be styled with CSS 10 Tecniche di programmazione A.A. 2012/2013
  • 11. Events  FX Event (javafx.event.Event):  Event Source => a Node  Event Target  Event Type  Usually generated after some user action  ActionEvent, TreeModificationEvent, InputEvent, ListView.E ditEvent, MediaErrorEvent, TableColumn.CellEditEvent,Tre eItem.TreeModificationEvent, TreeView.EditEvent, WebEve nt, WindowEvent, WorkerStateEvent  You can define event handlers in your application 11 Tecniche di programmazione A.A. 2012/2013
  • 12. Properties  Extension of the Java Beans convention  May be used also outside JavaFX  Encapsulate properties of an object  Different types (string, number, object, collection, ...)  Set/Get  Observe changes  Supports lazy evaluation  Each Node has a large set of Properties 12 Tecniche di programmazione A.A. 2012/2013
  • 13. Bindings  Automatically connect («bind») one Property to another Property  Whenever the source property changes, the bound one is automatically updated  Multiple bindings are supported  Lazy evaluation is supported  Bindings may also involve computations (arithmetic operators, if-then-else, string concatenation, ...) that are automatically evaluated  May be used to automate UI  May be used to connect the Model with the View 13 Tecniche di programmazione A.A. 2012/2013
  • 14. The Scene graph Introduction to JavaFX
  • 15. Nodes  Root node: top level container  Intermediate nodes:  Containers  Layout managers  UI Composite controls  Leaf (terminal) nodes:  Shapes  UI Controls  Organized as a Hierarchical tree 15 Tecniche di programmazione A.A. 2012/2013
  • 16. ChoiceBox ColorPicker ComboBoxBase Button ComboBox Nodes family CheckBox ButtonBase MenuButton Cell Labeled ToggleButton Label ListView Control TitledPane Group MenuBar Focus on Slider Panes TabPane and TextInputControl TextArea Controls TextField Parent ToolBar AnchorPane TreeView BorderPane Axis FlowPane Region Chart GridPane WebView Pane javafx.scene.Node Arc HBox JavaDoc StackPane is your friend Circle TilePane Line Shape VBox Polygon Canvas Rectangle Imageview 16 Text Tecniche di programmazione A.A. 2012/2013
  • 17. Exploring Controls and Examples  JavaFX Ensemble demo application  Download from Oracle site: JavaFX Demos and Samples Downloads  Run Ensemble.jnlp 17 Tecniche di programmazione A.A. 2012/2013
  • 18. UI Form Controls  Controls may be combined to construct «Forms»  Control Nodes have a value property  May be linked to application code  Control Nodes generate UI Events  Button: ActionEvent  Text: ActionEvent, KeyTyped, KeyPressed, MouseClicked, ... 18 Tecniche di programmazione A.A. 2012/2013
  • 19. 19 Tecniche di programmazione A.A. 2012/2013
  • 20. Layout Class Hierarchy  Group:  Doesn’t perform any positioning of children.  To statically assemble a collection of nodes in fixed positions  To apply an effect or transform to that collection.  Region:  base class for all general purpose layout panes  resizable and stylable via CSS  Supports dynamic layout by sizing and positioning children  Control:  the base class for all skinnable controls  resizable and subclasses are all stylable via CSS  Controls delegate layout to their skins (which are Regions)  Each layout Control subclass provides API for adding content in the appropriate place within its skin  you do not add children to a control directly. 20 Tecniche di programmazione A.A. 2012/2013
  • 21. 21 Tecniche di programmazione A.A. 2012/2013
  • 22. 22 Tecniche di programmazione A.A. 2012/2013
  • 23. 23 Tecniche di programmazione A.A. 2012/2013
  • 24. 24 Tecniche di programmazione A.A. 2012/2013
  • 25. 25 Tecniche di programmazione A.A. 2012/2013
  • 26. 26 Tecniche di programmazione A.A. 2012/2013
  • 27. 27 Tecniche di programmazione A.A. 2012/2013
  • 28. 28 Tecniche di programmazione A.A. 2012/2013
  • 29. Creating the Scene Graph  The Java way  Create Control Nodes  Set properties to new nodes  Add new nodes to parent node  With Constructors and/or with Builders  The FXML way  Create a FXML file  Define Nodes and Properties in FXML  Load the FXML  (Optionally, add new nodes/properties the Java way) 29 Tecniche di programmazione A.A. 2012/2013
  • 30. Example: one text input field TextField text = new TextField("Text"); Constructors text.setMaxSize(140, 20); root.getChildren().add(text); TextField text = TextFieldBuilder().create() .maxHeight(20).maxWidth(140) .text("Text") .build() ; Builders root.getChildren().add(text); 30 Tecniche di programmazione A.A. 2012/2013
  • 31. public class HelloDevoxx extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Hello Devoxx"); Group root = new Group(); Scene scene = new Scene(root, 400, 250, Color.ALICEBLUE); Text text = new Text(); text.setX(105); text.setY(120); text.setFont(new Font(30)); text.setText("Hello Devoxx"); root.getChildren().add(text); primaryStage.setScene(scene); primaryStage.show(); } } 31 Tecniche di programmazione A.A. 2012/2013
  • 32. public void start(Stage primaryStage) { primaryStage.setTitle("Hello Devoxx"); primaryStage.setScene(SceneBuilder.create() .width(400).height(250).fill(Color.ALICEBLUE) .root(GroupBuilder.create().children( TextBuilder.create() .x(105).y(120) .text("Hello Devoxx") .font(new Font(30)).build() ).build() ).build()); primaryStage.show(); } 32 Tecniche di programmazione A.A. 2012/2013
  • 33. The FXML way...  XML-based format  Nested tree of XML Elements, corresponding to Nodes  XML Attributes corresponding to (initial) properties of nodes  JavaFX Scene Builder is a GUI for creating FXML files  The FXMLLoader class reads a FXML file and creates all the Nodes 33 Tecniche di programmazione A.A. 2012/2013
  • 34. Example 34 Tecniche di programmazione A.A. 2012/2013
  • 35. JavaFX Scene Builder 35 Tecniche di programmazione A.A. 2012/2013
  • 36. FXMLLoader @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load( getClass().getResource("fxml_example.fxml")); stage.setTitle("FXML Welcome"); stage.setScene(new Scene(root, 300, 275)); stage.show(); } 36 Tecniche di programmazione A.A. 2012/2013
  • 37. Linking FXML and Java  FXML element may have an associated attribute fx:id  Nodes may be later retrieved by  public Node lookup(java.lang.String selector)  Finds a node with a specified ID in the current sub-tree  Example:  scene.lookup("#myId");  Node references can also be «injected» using the @FXML annotation (see later) 37 Tecniche di programmazione A.A. 2012/2013
  • 39. Interacting with Nodes  In JavaFX applications, events are notifications that something has happened.  An event represents an occurrence of something of interest to the application  As a user clicks a button, presses a key, moves a mouse, or performs other actions, events are dispatched.  Registered event filters and event handlers within the application  receive the event and  provide a response. 39 Tecniche di programmazione A.A. 2012/2013
  • 40. What is an event? 40 Tecniche di programmazione A.A. 2012/2013
  • 41. Event propagation  Events are generated on the source node  Events propagated in the scene graph hierarchy («dispatch chain»), in two phases  Dispatching: downwards, from root to source node  Processes Event Filters registered in the nodes  Bubbling: upwards, from source node to root  Processes Event Handlers registered in the nodes  If you want an application to be notified when an event occurs, register a filter or a handler for the event  Handlers may “consume” the event 41 Tecniche di programmazione A.A. 2012/2013
  • 42. Event Handlers  Implements the EventHandler interface  Executed during the event bubbling phase.  If does not consume the event, it is propagated to the parent.  A node can register more than one handler.  Handlers for a specific event type are executed before handlers for generic event types.  For example, a handler for the KeyEvent.KEY_TYPED event is called before the handler for the InputEvent.ANY event.  To consume an event, call the consume() method 42 Tecniche di programmazione A.A. 2012/2013
  • 43. Registering Event Handlers  setOnEvent-type( EventHandler<? super event-class> value )  Event-Type  The type of event that the handler processes (e.g. setOnKeyTyped, setOnMouseClicked, ...)  Event-class  The class that defines the event type (e.g., KeyEvent , MouseEvent, ...)  Value  The event handler for event-class (or for one of its super classes)  Must implement: public void handle(ActionEvent event)  May be a regular class or an anonymous inline class 43 Tecniche di programmazione A.A. 2012/2013
  • 44. Example class ButtonActionHandler implements Event Handler javafx.event.EventHandler<ActionEvent> { public ButtonActionHandler (/*params*/) { // constructor - if needed } @Override public void handle(ActionEvent event) { Button b = (Button)event.getSource() ; //...do something String buttonText = b.getText() ; // ... } Registration } Button btn = new Button() ; btn.setOnAction(new ButtonActionHandler()) ; 44 Tecniche di programmazione A.A. 2012/2013
  • 45. Example (inline definition) Registration & Anonymous event handler btn.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { System.out.println("Hello World"); } }); 45 Tecniche di programmazione A.A. 2012/2013
  • 46. To be continued... Properties and Bindings Introduction to JavaFX
  • 48. Resources  API  http://docs.oracle.com/javafx/2/api/index.html  Slides/Tips  http://www.slideshare.net/steveonjava/java-fx-20-a-developers-guide  http://refcardz.dzone.com/refcardz/getting-started-javafx  Tutorials/Articles  http://docs.oracle.com/javafx/2/events/jfxpub-events.htm  http://amyfowlersblog.wordpress.com/2011/06/02/javafx2-0-layout-a- class-tour/  Examples (Downloads)  JavaFX Demos and Samples, at http://www.oracle.com/technetwork/java/javase/downloads/jdk7- downloads-1880260.html 48 Tecniche di programmazione A.A. 2012/2013
  • 49. Licenza d’uso  Queste diapositive sono distribuite con licenza Creative Commons “Attribuzione - Non commerciale - Condividi allo stesso modo (CC BY-NC-SA)”  Sei libero:  di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico, rappresentare, eseguire e recitare quest'opera  di modificare quest'opera  Alle seguenti condizioni:  Attribuzione — Devi attribuire la paternità dell'opera agli autori originali e in modo tale da non suggerire che essi avallino te o il modo in cui tu usi l'opera.  Non commerciale — Non puoi usare quest'opera per fini commerciali.  Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se la usi per crearne un'altra, puoi distribuire l'opera risultante solo con una licenza identica o equivalente a questa.  http://creativecommons.org/licenses/by-nc-sa/3.0/ 49 Tecniche di programmazione A.A. 2012/2013