Session 9 |
Anonymous inner class handlers
An anonymous inner class is an inner class without a name. It combines defining an inner class and creating an instance of the class into one step.
Inner-class handlers can be shortened using anonymous inner classes. The inner class in previous part can be replaced by an anonymous inner class as shown below.
The syntax for an anonymous inner class is shown below
new SuperClassName/InterfaceName() { // Implement or override methods of the superclass or interface // Other methods if necessary }
Since an anonymous inner class is a special kind of inner classes, it is treated like an inner class with the following features:
- The anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit
extends
orimplements
clause. - The anonymous inner class must implement all the abstract methods in the superclass or in the interface.
- The anonymous inner class always uses the default constructor without arguments from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is
Object()
. - The anonymous inner class is compiled into a class named
OuterClassName$n.class
.
The following program demonstrates an anonymous inner class handler for the mouse event.
import javafx.application.Application; import javafx.event.ActionEvent; 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.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class ExampleRectangle extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { Group root = new Group(); Rectangle rect = new Rectangle(50, 50, 100, 100);; root.getChildren().add(rect); // Create and register anonymous inner class handler rect.setOnMouseEntered(new EventHandler<MouseEvent>(){ public void handle(MouseEvent event){ System.out.println("Mouse and rectangle"); rect.setFill(Color.THISTLE); } }); // Create scene and place it on the stage Scene scene = new Scene(root, 200, 200, Color.SNOW); primaryStage.setTitle("Rectangle"); primaryStage.setScene(scene); primaryStage.show(); } }
Try out
Try to run the program given above.
Session 9 |