Java Reference
In-Depth Information
public void start(Stage primaryStage) {
// Omitted
public void start(Stage primaryStage) {
// Omitted
btEnlarge.setOnAction(
new EnlargeHandler());
btEnla rge.setOnAction(
ne w class En largeHandlner
implements EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
circlePane.enlarge();
}
});
}
}
class EnlargeHandler
implements EventHandler<ActionEvent> {
public void handle(ActionEvent e) {
circlePane.enlarge();
}
}
(a) Inner class EnlargeListener
(b) Anonymous inner class
The syntax for an anonymous inner class is shown below
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or interface
// Other methods if necessary
}
Since an anonymous inner class is a special kind of inner class, it is treated like an inner class
with the following features:
An anonymous inner class must always extend a superclass or implement an inter-
face, but it cannot have an explicit extends or implements clause.
An anonymous inner class must implement all the abstract methods in the superclass
or in the interface.
An anonymous inner class always uses the no-arg constructor from its superclass to
create an instance. If an anonymous inner class implements an interface, the con-
structor is Object() .
An anonymous inner class is compiled into a class named OuterClassName$ n .
class . For example, if the outer class Test has two anonymous inner classes, they
are compiled into Test$1.class and Test$2.class .
Listing  15.4 gives an example that handles the events from four buttons, as shown in
Figure 15.8.
F IGURE 15.8
The program handles the events from four buttons.
L ISTING 15.4
AnonymousHandlerDemo.java
1 import javafx.application.Application;
2 import javafx.event.ActionEvent;
3 import javafx.event.EventHandler;
4 import javafx.geometry.Pos;
5 import javafx.scene.Scene;
VideoNote
Anonymous handler
 
 
Search WWH ::




Custom Search