- JavaFX Tutorial
- JavaFX - Home
- JavaFX - Overview
- JavaFX Installation and Architecture
- JavaFX - Environment
- JavaFX - Installation Using Netbeans
- JavaFX - Installation Using Eclipse
- JavaFX - Installation using Visual Studio Code
- JavaFX - Architecture
- JavaFX - Application
- JavaFX 2D Shapes
- JavaFX - 2D Shapes
- JavaFX - Drawing a Line
- JavaFX - Drawing a Rectangle
- JavaFX - Drawing a Rounded Rectangle
- JavaFX - Drawing a Circle
- JavaFX - Drawing an Ellipse
- JavaFX - Drawing a Polygon
- JavaFX - Drawing a Polyline
- JavaFX - Drawing a Cubic Curve
- JavaFX - Drawing a Quad Curve
- JavaFX - Drawing an Arc
- JavaFX - Drawing an SVGPath
- JavaFX Properties of 2D Objects
- JavaFX - Stroke Type Property
- JavaFX - Stroke Width Property
- JavaFX - Stroke Fill Property
- JavaFX - Stroke Property
- JavaFX - Stroke Line Join Property
- JavaFX - Stroke Miter Limit Property
- JavaFX - Stroke Line Cap Property
- JavaFX - Smooth Property
- Operations on 2D Objects
- JavaFX - 2D Shapes Operations
- JavaFX - Union Operation
- JavaFX - Intersection Operation
- JavaFX - Subtraction Operation
- JavaFX Path Objects
- JavaFX - Path Objects
- JavaFX - LineTo Path Object
- JavaFX - HLineTo Path Object
- JavaFX - VLineTo Path Object
- JavaFX - QuadCurveTo Path Object
- JavaFX - CubicCurveTo Path Object
- JavaFX - ArcTo Path Object
- JavaFX Color and Texture
- JavaFX - Colors
- JavaFX - Linear Gradient Pattern
- JavaFX - Radial Gradient Pattern
- JavaFX Text
- JavaFX - Text
- JavaFX Effects
- JavaFX - Effects
- JavaFX - Color Adjust Effect
- JavaFX - Color input Effect
- JavaFX - Image Input Effect
- JavaFX - Blend Effect
- JavaFX - Bloom Effect
- JavaFX - Glow Effect
- JavaFX - Box Blur Effect
- JavaFX - GaussianBlur Effect
- JavaFX - MotionBlur Effect
- JavaFX - Reflection Effect
- JavaFX - SepiaTone Effect
- JavaFX - Shadow Effect
- JavaFX - DropShadow Effect
- JavaFX - InnerShadow Effect
- JavaFX - Lighting Effect
- JavaFX - Light.Distant Effect
- JavaFX - Light.Spot Effect
- JavaFX - Point.Spot Effect
- JavaFX - DisplacementMap
- JavaFX - PerspectiveTransform
- JavaFX Transformations
- JavaFX - Transformations
- JavaFX - Rotation Transformation
- JavaFX - Scaling Transformation
- JavaFX - Translation Transformation
- JavaFX - Shearing Transformation
- JavaFX Animations
- JavaFX - Animations
- JavaFX - Rotate Transition
- JavaFX - Scale Transition
- JavaFX - Translate Transition
- JavaFX - Fade Transition
- JavaFX - Fill Transition
- JavaFX - Stroke Transition
- JavaFX - Sequential Transition
- JavaFX - Parallel Transition
- JavaFX - Pause Transition
- JavaFX - Path Transition
- JavaFX Images
- JavaFX - Images
- JavaFX 3D Shapes
- JavaFX - 3D Shapes
- JavaFX - Creating a Box
- JavaFX - Creating a Cylinder
- JavaFX - Creating a Sphere
- Properties of 3D Objects
- JavaFX - Cull Face Property
- JavaFX - Drawing Modes Property
- JavaFX - Material Property
- JavaFX Event Handling
- JavaFX - Event Handling
- JavaFX - Using Convenience Methods
- JavaFX - Event Filters
- JavaFX - Event Handlers
- JavaFX UI Controls
- JavaFX - UI Controls
- JavaFX - ListView
- JavaFX - Accordion
- JavaFX - ButtonBar
- JavaFX - ChoiceBox
- JavaFX - HTMLEditor
- JavaFX - MenuBar
- JavaFX - Pagination
- JavaFX - ProgressIndicator
- JavaFX - ScrollPane
- JavaFX - Separator
- JavaFX - Slider
- JavaFX - Spinner
- JavaFX - SplitPane
- JavaFX - TableView
- JavaFX - TabPane
- JavaFX - ToolBar
- JavaFX - TreeView
- JavaFX - Label
- JavaFX - CheckBox
- JavaFX - RadioButton
- JavaFX - TextField
- JavaFX - PasswordField
- JavaFX - FileChooser
- JavaFX - Hyperlink
- JavaFX - Tooltip
- JavaFX - Alert
- JavaFX - DatePicker
- JavaFX - TextArea
- JavaFX Charts
- JavaFX - Charts
- JavaFX - Creating Pie Chart
- JavaFX - Creating Line Chart
- JavaFX - Creating Area Chart
- JavaFX - Creating Bar Chart
- JavaFX - Creating Bubble Chart
- JavaFX - Creating Scatter Chart
- JavaFX - Creating Stacked Area Chart
- JavaFX - Creating Stacked Bar Chart
- JavaFX Layout Panes
- JavaFX - Layout Panes
- JavaFX - HBox Layout
- JavaFX - VBox Layout
- JavaFX - BorderPane Layout
- JavaFX - StackPane Layout
- JavaFX - TextFlow Layout
- JavaFX - AnchorPane Layout
- JavaFX - TilePane Layout
- JavaFX - GridPane Layout
- JavaFX - FlowPane Layout
- JavaFX CSS
- JavaFX - CSS
- Media with JavaFX
- JavaFX - Playing Video
- JavaFX Useful Resources
- JavaFX - Quick Guide
- JavaFX - Useful Resources
- JavaFX - Discussion
JavaFX - Event Handlers
Event handlers enable you to handle an event during the event bubbling phase of event processing.
The bubbling phase of an event route is a phase where the event travels from target node to stage node. Like Event filters, a node can have one or more handlers, or no handlers at all to handle an event. If the node does not contain a handler, the event reaches the root node and the process is completed. Otherwise, if a node in event dispatch chain contains a handler, the handler is executed.
A single handler can be used for more than one node and more than one event type. If an event handler for a child node does not consume the event, an event handler for a parent node enables the parent node to act on the event after a child node processes it and to provide common event processing for multiple child nodes.
Adding and Removing Event Handlers
To add an event handler to a node, you need to register this handler using the method addEventHandler() of the Node class as shown below.
//Creating the mouse event 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("Hello World"); circle.setFill(Color.DARKSLATEBLUE); } }; //Adding the event handler circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler);
In the same way, you can remove an event handler using the method removeEventHandler() as shown below −
circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);
Example
The following program is an example demonstrating the event handling in JavaFX using the event handlers.
Save this code in a file with 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.Color; 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 start(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 letter 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.BOLD, 15)); //Setting the color of the text text.setFill(Color.CRIMSON); //setting the position of the text text.setX(20); text.setY(50); //Setting the material of the box PhongMaterial material = new PhongMaterial(); material.setDiffuseColor(Color.DARKSLATEBLUE); //Setting the diffuse color material to box box.setMaterial(material); //Setting the rotation animation to the box RotateTransition rotateTransition = new RotateTransition(); //Setting the duration 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 cycle count for the transition rotateTransition.setCycleCount(50); //Setting auto reverse value to false 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 key typed event EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { //Playing the animation rotateTransition.play(); } }; //Adding an event handler to the text feld textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField); //Handling the mouse clicked event(on box) EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox = new EventHandler<javafx.scene.input.MouseEvent>() { @Override public void handle(javafx.scene.input.MouseEvent e) { rotateTransition.stop(); } }; //Adding the event 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); camera.setTranslateX(0); camera.setTranslateY(0); camera.setTranslateZ(0); scene.setCamera(camera); //Setting title to the Stage stage.setTitle("Event 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 following commands.
javac --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersExample.java java --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersExample
Output
On executing, the above program generates a JavaFX window displaying a text field and a 3D box as shown below −
Here, if you type a letter in the text field, the 3D box starts rotating along the x axis. If you click on the box again the rotation stops.
Example
Let us see another scenario where we can use Event Handlers. In this example, we are creating a JavaFX object, say a circle, and applying Fade Transition on it. Using an event handler, we are specifying when the Transition needs to be played and when to be paused; i.e. by clicking on a button.
Save this code in a file with name EventHandlersButton.java.
import javafx.animation.ScaleTransition; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class EventHandlerButton extends Application{ @Override public void start(Stage primaryStage) throws Exception { // TODO Auto-generated method stub //Creating Circle and setting the color and stroke in the circle Circle c = new Circle(150, 125, 50); c.setFill(Color.RED); c.setStroke(Color.BLACK); //creating play button and setting coordinates for the button Button btn = new Button("Play"); btn.setTranslateX(100); btn.setTranslateY(250); // creating pause button and setting coordinate for the pause button Button btn1 = new Button("Pause"); btn1.setTranslateX(150); btn1.setTranslateY(250); //Instantiating TranslateTransition class to create the animation ScaleTransition st = new ScaleTransition(); //setting attributes for the TranslateTransition st.setNode(c); st.setDuration(Duration.millis(1000)); st.setByX(1); st.setByY(1); st.setAutoReverse(true); st.setCycleCount(50); //Creating EventHandler EventHandler<MouseEvent> handler = new EventHandler() { @Override public void handle(MouseEvent event) { // TODO Auto-generated method stub if(event.getSource()==btn) { st.play(); //animation will be played when the play button is clicked } if(event.getSource()==btn1) { st.pause(); //animation will be paused when the pause button is clicked } event.consume(); } }; //Adding Handler for the play and pause button btn.setOnMouseClicked(handler); btn1.setOnMouseClicked(handler); // Creating Group Object Group root = new Group(); root.getChildren().addAll(c, btn, btn1); // Creating Scene Object Scene scene = new Scene(root, 300, 300); primaryStage.setScene(scene); // Adding Title to Application primaryStage.setTitle("EventHandler Button"); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
Compile and execute the saved java file from the command prompt using the following commands.
javac --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersButton.java java --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersButton
Output
On executing, the above program generates a JavaFX window displaying a circle with fade transition.