banner



How To Register As Only One Keyboard Press In Javafx

JavaFX - Outcome Handling


In JavaFX, we can develop GUI applications, web applications and graphical applications. In such applications, whenever a user interacts with the awarding (nodes), an event is said to have been occurred.

For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the folio are the activities that causes an effect to happen.

Types of Events

The events can be broadly classified into the following two categories −

  • Foreground Events − Those events which require the straight interaction of a user. They are generated equally consequences of a person interacting with the graphical components in a Graphical User Interface. For example, clicking on a button, moving the mouse, inbound a character through keyboard, selecting an item from listing, scrolling the page, etc.

  • Groundwork Events − Those events that don't require the interaction of end-user are known as background events. The operating system interruptions, hardware or software failure, timer expiry, operation completion are the example of background events.

Events in JavaFX

JavaFX provides back up to handle a wide varieties of events. The class named Issue of the package javafx.event is the base class for an effect.

An instance of any of its bracket is an event. JavaFX provides a broad variety of events. Some of them are are listed below.

  • Mouse Consequence − This is an input event that occurs when a mouse is clicked. It is represented by the class named MouseEvent. Information technology includes actions similar mouse clicked, mouse pressed, mouse released, mouse moved, mouse entered target, mouse exited target, etc.

  • Key Event − This is an input upshot that indicates the key stroke occurred on a node. It is represented past the class named KeyEvent. This event includes deportment like fundamental pressed, fundamental released and key typed.

  • Drag Event − This is an input event which occurs when the mouse is dragged. It is represented by the form named DragEvent. It includes actions similar drag entered, elevate dropped, drag entered target, elevate exited target, drag over, etc.

  • Window Upshot − This is an upshot related to window showing/hiding deportment. Information technology is represented past the class named WindowEvent. It includes actions like window hiding, window shown, window subconscious, window showing, etc.

Event Treatment

Issue Handling is the mechanism that controls the event and decides what should happen, if an event occurs. This machinery has the code which is known equally an effect handler that is executed when an event occurs.

JavaFX provides handlers and filters to handle events. In JavaFX every event has −

  • Target − The node on which an upshot occurred. A target tin be a window, scene, and a node.

  • Source − The source from which the outcome is generated will be the source of the effect. In the above scenario, mouse is the source of the effect.

  • Type − Blazon of the occurred event; in case of mouse event – mouse pressed, mouse released are the type of events.

Assume that we have an application which has a Circumvolve, Cease and Play Buttons inserted using a group object every bit follows −

Sample Application

If y'all click on the play push button, the source volition be the mouse, the target node will be the play button and the blazon of the consequence generated is the mouse click.

Phases of Event Handling in JavaFX

Whenever an outcome is generated, JavaFX undergoes the post-obit phases.

Route Construction

Whenever an event is generated, the default/initial route of the event is adamant by construction of an Event Dispatch concatenation. It is the path from the stage to the source Node.

Following is the upshot dispatch concatenation for the result generated, when we click on the play push button in the above scenario.

Play Button

Consequence Capturing Phase

After the construction of the issue acceleration chain, the root node of the application dispatches the issue. This event travels to all nodes in the dispatch chain (from top to bottom). If whatsoever of these nodes has a filter registered for the generated event, it will be executed. If none of the nodes in the dispatch concatenation has a filter for the event generated, and then it is passed to the target node and finally the target node processes the result.

Event Bubbling Phase

In the event bubbles phase, the event is travelled from the target node to the stage node (lesser to top). If any of the nodes in the event dispatch chain has a handler registered for the generated event, it will be executed. If none of these nodes take handlers to handle the event, and so the event reaches the root node and finally the procedure will be completed.

Event Handlers and Filters

Upshot filters and handlers are those which contains application logic to procedure an issue. A node tin can register to more than than one handler/filter. In case of parent–child nodes, you can provide a common filter/handler to the parents, which is processed as default for all the child nodes.

As mentioned above, during the result, processing is a filter that is executed and during the issue bubbling phase, a handler is executed. All the handlers and filters implement the interface EventHandler of the package javafx.consequence.

Adding and Removing Result Filter

To add an result filter to a node, you demand to register this filter using the method addEventFilter() of the Node form.

//Creating the mouse event handler  EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {     @Override     public void handle(MouseEvent e) {        Organisation.out.println("Hello World");        circumvolve.setFill(Colour.DARKSLATEBLUE);      }  };    //Calculation consequence Filter  Circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);        

In the aforementioned way, you can remove a filter using the method removeEventFilter() as shown below −

circle.removeEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);        

Event Handling Example

Following is an example demonstrating the issue handling in JavaFX using the event filters. Salvage this code in a file with name EventFiltersExample.coffee.

import javafx.application.Application;  import static javafx.application.Awarding.launch;  import javafx.issue.EventHandler;   import javafx.scene.Group;  import javafx.scene.Scene;  import javafx.scene.input.MouseEvent;  import javafx.scene.pigment.Color;  import javafx.scene.shape.Circle;   import javafx.scene.text.Font;  import javafx.scene.text.FontWeight; import javafx.scene.text.Text;  import javafx.stage.Stage;            public class EventFiltersExample extends Application {     @Override     public void start(Stage phase) {             //Drawing a Circumvolve        Circle circle = new Circle();               //Setting the position of the circle        circle.setCenterX(300.0f);        circle.setCenterY(135.0f);               //Setting the radius of the circle        circle.setRadius(25.0f);               //Setting the color of the circle        circumvolve.setFill(Color.BROWN);               //Setting the stroke width of the circumvolve        circle.setStrokeWidth(20);                     //Setting the text        Text text = new Text("Click on the circle to change its color");               //Setting the font of the text        text.setFont(Font.font(zip, FontWeight.Assuming, xv));                   //Setting the color of the text        text.setFill(Colour.CRIMSON);           //setting the position of the text        text.setX(150);        text.setY(50);                //Creating the mouse event handler        EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {           @Override           public void handle(MouseEvent due east) {              System.out.println("Howdy Earth");              circle.setFill(Color.DARKSLATEBLUE);          }        };         //Registering the event filter        circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);                  //Creating a Group object         Grouping root = new Group(circumvolve, text);                  //Creating a scene object        Scene scene = new Scene(root, 600, 300);                //Setting the fill color to the scene        scene.setFill(Color.Lavander);                //Setting championship to the Phase        stage.setTitle("Event Filters Case");                        //Adding scene to the stage        stage.setScene(scene);                  //Displaying the contents of the stage        phase.prove();     }     public static void main(String args[]){        launch(args);     }  }        

Compile and execute the saved java file from the control prompt using the following commands.

javac EventFiltersExample.coffee  java EventFiltersExample        

On executing, the higher up programme generates a JavaFX window as shown below.

Change Color

Adding and Removing Event Handlers

To add an outcome handler to a node, you demand to register this handler using the method addEventHandler() of the Node class as shown below.

//Creating the mouse upshot handler  EventHandler<javafx.scene.input.MouseEvent> eventHandler =     new EventHandler<javafx.scene.input.MouseEvent>() {         @Override     public void handle(javafx.scene.input.MouseEvent e) {        System.out.println("Hi World");        circle.setFill(Color.DARKSLATEBLUE);                 }  };     //Adding the event handler  circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler);        

In the same way, you tin remove an event handler using the method removeEventHandler() as shown beneath −

circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);        

Example

The following program is an instance demonstrating the event handling in JavaFX using the event handlers.

Save this code in a file with proper name EventHandlersExample.java.

import javafx.animation.RotateTransition;  import javafx.application.Application;  import javafx.event.EventHandler;   import javafx.scene.Group;  import javafx.scene.PerspectiveCamera;  import javafx.scene.Scene;  import javafx.scene.control.TextField;  import javafx.scene.input.KeyEvent;  import javafx.scene.paint.Colour;  import javafx.scene.paint.PhongMaterial;   import javafx.scene.shape.Box;  import javafx.scene.text.Font;  import javafx.scene.text.FontWeight;  import javafx.scene.text.Text;   import javafx.scene.transform.Rotate;  import javafx.stage.Stage;  import javafx.util.Duration;            public class EventHandlersExample extends Application {         @Override     public void kickoff(Stage stage) {       //Drawing a Box        Box box = new Box();               //Setting the properties of the Box        box.setWidth(150.0);        box.setHeight(150.0);          box.setDepth(100.0);                //Setting the position of the box        box.setTranslateX(350);         box.setTranslateY(150);        box.setTranslateZ(50);                //Setting the text        Text text = new Text("Type any alphabetic character to rotate the box,           and click on the box to stop the rotation");               //Setting the font of the text        text.setFont(Font.font(null, FontWeight.Assuming, fifteen));                   //Setting the colour of the text        text.setFill(Color.CRIMSON);               //setting the position of the text        text.setX(twenty);        text.setY(50);                //Setting the material of the box        PhongMaterial material = new PhongMaterial();         material.setDiffuseColor(Colour.DARKSLATEBLUE);                //Setting the lengthened colour material to box        box.setMaterial(material);                      //Setting the rotation animation to the box           RotateTransition rotateTransition = new RotateTransition();               //Setting the elapsing for the transition        rotateTransition.setDuration(Duration.millis(1000));               //Setting the node for the transition        rotateTransition.setNode(box);                     //Setting the axis of the rotation        rotateTransition.setAxis(Rotate.Y_AXIS);               //Setting the angle of the rotation       rotateTransition.setByAngle(360);               //Setting the bicycle count for the transition        rotateTransition.setCycleCount(50);               //Setting auto reverse value to faux        rotateTransition.setAutoReverse(false);                //Creating a text filed        TextField textField = new TextField();                 //Setting the position of the text field        textField.setLayoutX(50);        textField.setLayoutY(100);                //Handling the cardinal typed event        EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {           @Override           public void handle(KeyEvent effect) {              //Playing the animation              rotateTransition.play();           }                  };                     //Adding an outcome handler to the text feld        textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);                //Handling the mouse clicked effect(on box)        EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =           new EventHandler<javafx.scene.input.MouseEvent>() {                     @Override           public void handle(javafx.scene.input.MouseEvent e) {              rotateTransition.cease();            }        };        //Calculation the outcome handler to the box         box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox);               //Creating a Group object       Group root = new Group(box, textField, text);                  //Creating a scene object        Scene scene = new Scene(root, 600, 300);                    //Setting camera        PerspectiveCamera camera = new PerspectiveCamera(false);        photographic camera.setTranslateX(0);        camera.setTranslateY(0);        camera.setTranslateZ(0);        scene.setCamera(camera);                //Setting championship to the Phase        stage.setTitle("Outcome Handlers Example");                  //Adding scene to the stage        stage.setScene(scene);                  //Displaying the contents of the stage        stage.show();     }     public static void main(String args[]){        launch(args);     }  }        

Compile and execute the saved java file from the command prompt using the post-obit commands.

javac EventHandlersExample.java  java EventHandlersExample        

On executing, the above program generates a JavaFX window displaying a text field and a 3D box equally shown beneath −

Text Field

Here, if you lot type a letter in the text field, the 3D box starts rotating along the x axis. If you click on the box over again the rotation stops.

Using Convenience Methods for Event Treatment

Some of the classes in JavaFX ascertain outcome handler properties. By setting the values to these properties using their corresponding setter methods, you can register to an event handler. These methods are known as convenience methods.

Most of these methods exist in the classes like Node, Scene, Window, etc., and they are bachelor to all their sub classes.

For example, to add a mouse event listener to a button, you tin employ the convenience method setOnMouseClicked() equally shown below.

playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {     public void handle(MouseEvent event) {        Organisation.out.println("Hullo World");        pathTransition.play();     }  }));        

Example

The post-obit plan is an example that demonstrates the event handling in JavaFX using the convenience methods.

Save this lawmaking in a file with the name ConvinienceMethodsExample.java.

import javafx.animation.PathTransition;  import javafx.awarding.Application;  import static javafx.application.Awarding.launch;  import javafx.result.EventHandler;   import javafx.scene.Group;  import javafx.scene.Scene;  import javafx.scene.control.Push;  import javafx.scene.input.MouseEvent;  import javafx.scene.pigment.Colour;   import javafx.scene.shape.Circle;  import javafx.scene.shape.LineTo;  import javafx.scene.shape.MoveTo;  import javafx.scene.shape.Path;  import javafx.phase.Stage;  import javafx.util.Duration;            public form ConvinienceMethodsExample extends Application {     @Override     public void start(Stage stage) {             //Drawing a Circumvolve        Circle circumvolve = new Circle();               //Setting the position of the circle        circumvolve.setCenterX(300.0f);        circumvolve.setCenterY(135.0f);               //Setting the radius of the circle        circumvolve.setRadius(25.0f);                //Setting the color of the circle        circumvolve.setFill(Color.BROWN);               //Setting the stroke width of the circle        circumvolve.setStrokeWidth(xx);                     //Creating a Path        Path path = new Path();               //Moving to the staring point        MoveTo moveTo = new MoveTo(208, 71);                             //Creating 1st line        LineTo line1 = new LineTo(421, 161);                      //Creating 2d line        LineTo line2 = new LineTo(226,232);               //Creating 3rd line        LineTo line3 = new LineTo(332,52);                      //Creating quaternary line        LineTo line4 = new LineTo(369, 250);                      //Creating 5th line        LineTo line5 = new LineTo(208, 71);                     //Adding all the elements to the path        path.getElements().add(moveTo);        path.getElements().addAll(line1, line2, line3, line4, line5);                   //Creating the path transition        PathTransition pathTransition = new PathTransition();               //Setting the duration of the transition        pathTransition.setDuration(Elapsing.millis(1000));                     //Setting the node for the transition        pathTransition.setNode(circumvolve);               //Setting the path for the transition        pathTransition.setPath(path);               //Setting the orientation of the path        pathTransition.setOrientation(          PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT);              //Setting the cycle count for the transition        pathTransition.setCycleCount(50);               //Setting auto reverse value to true        pathTransition.setAutoReverse(fake);              //Creating play button        Push button playButton = new Button("Play");        playButton.setLayoutX(300);        playButton.setLayoutY(250);                circumvolve.setOnMouseClicked (new EventHandler<javafx.scene.input.MouseEvent>() {           @Override           public void handle(javafx.scene.input.MouseEvent e) {              Organisation.out.println("Hi Globe");              circumvolve.setFill(Color.DARKSLATEBLUE);                       }        });          playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {           public void handle(MouseEvent upshot) {              System.out.println("Hello World");               pathTransition.play();           }        }));                //Creating stop push        Push stopButton = new Button("stop");        stopButton.setLayoutX(250);        stopButton.setLayoutY(250);               stopButton.setOnMouseClicked((new EventHandler<MouseEvent>() {           public void handle(MouseEvent event) {              System.out.println("Hullo World");              pathTransition.stop();           }        }));       //Creating a Group object         Group root = new Group(circle, playButton, stopButton);                  //Creating a scene object        Scene scene = new Scene(root, 600, 300);        scene.setFill(Color.LAVENDER);                //Setting championship to the Stage        stage.setTitle("Convenience Methods Example");                   //Calculation scene to the stage        stage.setScene(scene);                  //Displaying the contents of the stage        stage.bear witness();     }     public static void primary(String args[]){        launch(args);     }  }        

Compile and execute the saved java file from the command prompt using the following commands.

javac ConvinienceMethodsExample.coffee  java ConvinienceMethodsExample        

On executing, the above plan generates a JavaFX window every bit shown below. Here click on the play button to start the blitheness and click on the finish button to stop the blitheness.

Convinience Method

Useful Video Courses


Advanced Java Using Eclipse IDE: Learn JavaFX &amp; Databases

Video

Complete Oracle JavaFX Bootcamp! Build Real Projects In 2021

Video

JavaFX Database Management System! Database Design In JavaFX

Video

How To Register As Only One Keyboard Press In Javafx,

Source: https://www.tutorialspoint.com/javafx/javafx_event_handling.htm

Posted by: mullensracter1947.blogspot.com

0 Response to "How To Register As Only One Keyboard Press In Javafx"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel