Java Reference
In-Depth Information
6
import
javafx.scene.control.Button;
7
import
javafx.scene.layout.HBox;
8
import
javafx.stage.Stage;
9
10
public class
AnonymousHandlerDemo
extends
Application {
11 @Override
// Override the start method in the Application class
12
public void
start(Stage primaryStage) {
13
// Hold two buttons in an HBox
14 HBox hBox =
new
HBox();
15 hBox.setSpacing(
10
);
16 hBox.setAlignment(Pos.CENTER);
17 Button btNew =
new
Button(
"New"
);
18 Button btOpen =
new
Button(
"Open"
);
19 Button btSave =
new
Button(
"Save"
);
20 Button btPrint =
new
Button(
"Print"
);
21 hBox.getChildren().addAll(btNew, btOpen, btSave, btPrint);
22
23
// Create and register the handler
24 btNew.setOnAction(
new
EventHandler<ActionEvent>() {
25 @Override
// Override the handle method
26
anonymous handler
public void
handle(ActionEvent e) {
handle event
27
System.out.println(
"Process New"
);
28
}
29
});
30
31 btOpen.setOnAction(
new
EventHandler<ActionEvent>() {
32 @Override
// Override the handle method
33
public void
handle(ActionEvent e) {
34 System.out.println(
"Process Open"
);
35 }
36 });
37
38 btSave.setOnAction(
new
EventHandler<ActionEvent>() {
39 @Override
// Override the handle method
40
public void
handle(ActionEvent e) {
41 System.out.println(
"Process Save"
);
42 }
43 });
44
45 btPrint.setOnAction(
new
EventHandler<ActionEvent>() {
46 @Override
// Override the handle method
47
public void
handle(ActionEvent e) {
48 System.out.println(
"Process Print"
);
49 }
50 });
51
52
// Create a scene and place it in the stage
53 Scene scene =
new
Scene(hBox,
300
,
50
);
54 primaryStage.setTitle(
"AnonymousHandlerDemo"
);
// Set title
55 primaryStage.setScene(scene);
// Place the scene in the stage
56 primaryStage.show();
// Display the stage
57 }
58 }
The program creates four handlers using anonymous inner classes (lines 24-50). Without
using anonymous inner classes, you would have to create four separate classes. An anony-
mous handler works the same way as that of an inner class handler. The program is condensed
using an anonymous inner class.
Search WWH ::
Custom Search