Session 9 |
Inner classes
An inner class, or nested class, is a class defined within the scope of another class. Inner classes are useful for defining handler classes.
The inner class may be used just like a regular class. Normally, we define a class as an inner class if it is used only by its outer class. The inner class has the following features:
- The inner class is compiled into a class named
OuterClassName$InnerClassName.class
. - The inner class can reference the data and the methods defined in the outer class in which it nests, so we do not need to pass the reference of the outer class's object to the constructor of the inner class. For this reason, inner classes can make programs simple and concise.
A simple use of inner classes is to combine dependent classes into a primary class. This reduces the number of source files. A handler class is designed specifically to create a handler object for a GUI component (e.g., a button). The handler class will not be shared by other applications and therefore is appropriate to be defined inside the main class as an inner class.
We now write a program that uses a button to control the size of a circle. When the Enlarge button is clicked, the circle will be repainted with a larger radius. To make the reference variable
circle
accessible from the handle
method, the handler class EnlargeHandler
is defined as an
inner class of the EnlargeCircle
class.
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.VBox; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.scene.paint.Color; public class EnlargeCircle extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { //hold circle and button in VBox VBox root = new VBox(); Circle circle = new Circle(50, Color.RED); Button btEnlarge = new Button("Enlarge"); root.getChildren().addAll(circle,btEnlarge); //handler class class EnlargeHandler implements EventHandler<ActionEvent> { public void handle(ActionEvent event){ circle.setRadius(circle.getRadius() + 2); } } // Create and register the handler btEnlarge.setOnAction(new EnlargeHandler()); // Create a scene and place it in the stage Scene scene = new Scene(root, 200, 250, Color.SNOW); primaryStage.setTitle("Circle"); primaryStage.setScene(scene); primaryStage.show(); } }
Try out
Try to run the program given above.
As an exercise, add the second button (named Shrink) and the code for handling the Shrink button to display a smaller circle when the Shrink button is clicked.
Session 9 |