Friday, November 1, 2019

Basic JavaFX projects (Part 3)

JavaFX Mouse Event Registration And Propagation

This is an examination of registering InputEvents, in this case MouseEvents (clicked), Event propagation, and how the registered methods are called in response to the Event propagation.

The code can be cloned from github.com as before.  The link is https://github.com/cajanssen/JavaFXMouseEventRegistration.git  Refer to earlier postings for advice on how to bring a GitHub project into Eclipse.

The JavaFX user interface, like many other user interface frameworks, is built upon a nested tree of user interface objects.  (JavaFX uses the term "scene graph".)  In the JavaFX case, it is the scene graph is a collection of Node objects.  Note that the "root" Node ("root" being the top of the content tree) actually needs to be a Parent, which is a direct subclass of Node.  (Stage -> Scene -> Parent -> many Node(s))  The Stage is the equivalent of a window, and if more than one window is desired for an application, additional Stage objects must be created.

https://openjfx.io/javadoc/13/javafx.graphics/javafx/stage/Stage.html
https://openjfx.io/javadoc/13/javafx.graphics/javafx/scene/Scene.html
https://openjfx.io/javadoc/13/javafx.graphics/javafx/scene/Node.html
https://openjfx.io/javadoc/13/javafx.graphics/javafx/scene/Parent.html

Note that, as evidenced by the URL, the documentation links point to a specific version of JavaFX (i.e., 13).  So, depending upon how Gluon maintains the documentation over time, these links may eventually break.  Currently, links back through version 11 are active.

Since this user interface is a nested tree, user interface events will occur within the visual bounding area of more than one object (i.e. the topmost object, its parent, its grandparent, etc.).  These events will propagate through the tree (scene graph) such that all the relevant objects have a chance at reacting to them.   The user interface objects can have EventHandler objects attached to them in two ways: via Event filters and via Event handlers.  The difference between these two is when they execute.  Events propagate down the tree from the top in what is called the capturing phase.  Event filters are called during this time.  When the bottom of the tree is reached, the Event propagates back up the tree in what is called the bubbling phase.  Event handlers are called during this time.  Event propagation can be halted at any time by calling consume() on the actual Event in the handler code.  (In the code below, e.consume() in the handle() method of one of the EventHandler objects.)

Example code:

package jansproj.basicfx;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class MouseEventRegistration extends Application
{
    public MouseEventRegistration()
    {
    }

    // this application waits for and reacts to mouse click events
   
    @Override
    public void start(Stage stage) throws Exception
    {
        // Stage, Scene, root Node - standard stuff common to JavaFX programs
        stage.setTitle("Mouse Event Example");
        Group root = new Group();
        Scene scene = new Scene(root);
        stage.setScene(scene);

        int canvasWidth = 1000;
        int canvasHeight = 500;
        int canvasXCenter = canvasWidth / 2;
        int canvasYCenter = canvasHeight / 2;

        Canvas canvas = new Canvas(canvasWidth, canvasHeight);
       
        // rather than create a large tree of nodes, create a tree of only
        // one node - canvas - and draw on that
        Group extraGroup = new Group();
        extraGroup.getChildren().add(canvas);
        root.getChildren().add(extraGroup);

       
        double blackCircleRadius = 250;
        double blueCircleRadius = 200;
        double redCircleRadius = 150;
        double goldCircleRadius = 100;

        // make concentric circles
        // drawing point for strokeOval() is the upper left corner of bounding box, not the center
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setLineWidth(4.0);
        gc.setStroke(Color.BLACK);
        gc.strokeOval((canvasXCenter - blackCircleRadius), (canvasYCenter - blackCircleRadius), blackCircleRadius*2, blackCircleRadius*2);
         gc.setStroke(Color.BLUE);
        gc.strokeOval((canvasXCenter - blueCircleRadius), (canvasYCenter - blueCircleRadius), blueCircleRadius*2, blueCircleRadius*2);
        gc.setStroke(Color.RED);
        gc.strokeOval((canvasXCenter - redCircleRadius), (canvasYCenter - redCircleRadius), redCircleRadius*2, redCircleRadius*2);
        gc.setStroke(Color.GOLD);
        gc.strokeOval((canvasXCenter - goldCircleRadius), (canvasYCenter - goldCircleRadius), goldCircleRadius*2, goldCircleRadius*2);

       
        // attach a Mouse Click event handler to the scene
        // rather than create the object elsewhere and pass it in to the setOnMouseClicked()
        // method, define the event handler right here with
        // an anonymous inner class - common practice
        scene.setOnMouseClicked(
            new EventHandler<MouseEvent>()
            {
                public void handle(MouseEvent e)
                { System.out.println("Scene event handler (via set)"); }
            });
        root.setOnMouseClicked(
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("Root (Group) event handler (via set)"); e.consume();}
                });
        extraGroup.setOnMouseClicked(
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("ExtraGroup event handler (via set) #1"); }
                });
        extraGroup.setOnMouseClicked(
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("ExtraGroup event handler (via set) #2"); }
                });
        extraGroup.addEventHandler(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    {  System.out.println("ExtraGroup event handler #1 (via add)"); }
                });
        extraGroup.addEventHandler(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    {  System.out.println("ExtraGroup event handler #2 (via add)"); }
                });
        extraGroup.addEventHandler(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    {  System.out.println("ExtraGroup event handler #3 (via add)"); }
                });
        canvas.setOnMouseClicked(
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("Canvas event handler (via set)"); }
                });
        scene.addEventFilter(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("Scene event filter #1"); };
                });
        scene.addEventFilter(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("Scene event filter #2"); }
                });
        scene.addEventFilter(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("Scene event filter #3"); };
                });
        root.addEventFilter(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("Root (Group) event filter"); }
                });
        extraGroup.addEventFilter(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("ExtraGroup event filter"); }
                });
        canvas.addEventFilter(MouseEvent.MOUSE_CLICKED,
                new EventHandler<MouseEvent>()
                {
                    public void handle(MouseEvent e)
                    { System.out.println("Canvas event filter"); }
                });

        // calling show() on the Stage is a standard requirement for a JavaFX program
        stage.show();
    }

    public static void main(String[] args)
    {
        launch(args);
    }
}


Note that due to the redundancy in this code, it is compressed and formatted less explicitly than might be expected.
Also note that the second Group object, named "extraGroup" in the code, is gratuitous and is only in the code to add depth to the user interface object tree to better display the propagation of events.
During the execution of the application, the mouse clicks will cause each EventHandler object to print to the console an identification of itself, providing a listing of the order in which they executed.

Event filters (EventHandler objects) to be executed during the capture phase are added via the addEventFilter() method.  Note that multiple event filters can be added to each Node type object.  Also, it would appear filters execute in order added.  However, it is not specified as such in the documentation.  Therefore, it would be prudent not to assume that to be guaranteed behavior.  Even if an examination of the source for the framework libraries did show this to be true, if it is not specified in the interface contract (and written in the documentation somewhere) it could change at any time in the future as library components are updated.


Event handlers (again, EventHandler objects) to be executed during the bubbling phase can be added in two ways - with the setOnMouseClicked method (name of the method depends upon event being handled) and the addEventHandler method (type of the event passed as a parameter).  As can be see in examining and executing the example code, only one handler can be added with setOnMouseClicked().  Any subsequent calls on the same Node (or descendant) object overwrites the first handler.  Multiple handlers can be added with addEventHandler().  Also as is seen in the example code, calls to setOnMouseClicked() and addEventHandler() do not interfere with each other.

Finally, note that during execution two of the created handler objects never get called.  The first, "ExtraGroup event handler #1", because another setOnMouseClicked called overwrote the first handler.  (As mentioned above.)  For the second, "Scene event handler", e.consume() is called in the root Event handler and stops propagation before it makes it back up to the top.  The handler "Scene event handler" would have been called at the very end.

No comments:

Post a Comment