JavaFX Event Filter

0

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(){
@override
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
node1.addEventFilter(ActionEvent.ROOT,filter);

Code for registering an EventFilter for single Node AS


node.addEventFilter(ActionEvent.ROOT,
 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 JavaFXtuts.com
 */
public class Javafxtuts extends Application {
    
    @Override
    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() {
        @Override 
        public void handle(MouseEvent event) {
            btn.setText("One clicked");
 }
 };
        btn.addEventFilter(MouseEvent.MOUSE_PRESSED,filter);
        btn1.addEventFilter(MouseEvent.MOUSE_PRESSED,filter);
        HBox root = new HBox();
        //to set the position of hbox(root) in center
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(btn,btn1);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("javafxtuts.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Output:

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() {
        @Override 
        public void handle(MouseEvent event) {
            btn.setText("One clicked");
 }
 };

And add filter to the node as

btn.addEventFilter(MouseEvent.MOUSE_PRESSED,filter);
Here event-type is MouseEvent. Mouse_pressed which is a sub-class of MouseEvent, so we can apply it.

Share.

Leave A Reply