cbinder
cbinder

Reputation: 2506

EventHandler<T extends Event> in JavaFX a class or interface

I have picked a basic example of printing "Hello World" on screen when the mouse is clicked The code goes like this.

package sample;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @author gauravp
 */
public class Sample extends Application {

    /**
     * @param args the command line arguments
     */
    Button btn = new Button("ok");
    //Label l = new Label("Done");

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

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("First Stage");


        //Created anonymous inner class EventHandler<ActionEvent>
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {

                    System.out.print("Hello World !!");


            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}

In documentation it is mentioned that EventHandler is an interface , but how come the interface be instantiated...

"new EventHandler<ActionEvent>()"

In a lot of confusion....please reply if you have any idea.. Here is the link for the EventHandler interface : http://docs.oracle.com/javafx/2.0/api/javafx/event/EventHandler.html

Upvotes: 1

Views: 9251

Answers (2)

Jesper
Jesper

Reputation: 206816

What you're seeing there is an anonymous inner class.

It's an implementation of the interface "on the spot", without creating a separate class with a name that implements the interface.

Anonymous inner classes are often used for event handlers of GUI components, as your example code shows.

Upvotes: 1

ARRG
ARRG

Reputation: 2496

The syntax

    new EventHandler<ActionEvent>() {
        @Override // <- notice the annotation, it overrides from the interface.
        public void handle(ActionEvent event) {
                System.out.print("Hello World !!");
        }
    }

creates an "anonymous inner class" that implements EventHandler, and defines the handle method. If you inspect the classes generated when you compile your project, you will probably find a class file named Sample$1 (or similar) which is the class generated for this code.

You can read up on inner (anonymous) classes here: http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

To answer your question: EventHandler is an interface, and this code doesn't actually create an instance of it, but an instance of the newly declared anonymous class.

Upvotes: 4

Related Questions