JavaFX Event Filter


JavaFX Event Filter Tutorial:

Event Filter is similar to EventHandler.

Event filter executed during the event capturing phase.

One or more filters per node.

Code for creating Event Filter :

EventHandler filter =new EventHandler(){
public void handle(ActionEvent event){
//write code

Register event filter :

To register This EventFilter We use addEventFilter() method as

node.addEventFilter(ActionEvent.ROOT, filter);

Adding same filter to different nodes AS

Code for registering an EventFilter for single Node AS

 new EventHandler() {
 @Override public void handle(ActionEvent event) {
// write code here

addEventFilter is taking two arguments Event-type and filter.

Remove an event filter:

We remove the event filter using RemoveEventFilter() method.
It also takes two arguments event-type and filter. As

node.removeEventFilter(ActionEvent.ROOT, filter);

Example of event filter:

package javafxtuts;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

 * @author
public class Javafxtuts extends Application {
    public void start(Stage primaryStage) {
        Button btn = new Button();
        Button btn1 = new Button();
        btn.setText("click button");
        btn1.setText("My button");
        EventHandler filter=new EventHandler() {
        public void handle(MouseEvent event) {
            btn.setText("One clicked");
        HBox root = new HBox();
        //to set the position of hbox(root) in center
        Scene scene = new Scene(root, 300, 250);

     * @param args the command line arguments
    public static void main(String[] args) {


Explanation of event filter example:

First, create an Event filter and we set the event-type for filtering(handling) is MouseEvent.

And we want to change the button text when a mouse pressed so we write code as

  EventHandler filter=new EventHandler() {
        public void handle(MouseEvent event) {
            btn.setText("One clicked");

And add filter to the node as

Here event-type is MouseEvent. Mouse_pressed which is a sub-class of MouseEvent, so we can apply it.


Leave A Reply