Java Reference
In-Depth Information
The
EventHandler<ActionEvent>
interface contains the
handle(ActionEvent)
method for processing the action event. Your handler class must override this method to
respond to the event. Listing 15.1 gives the code that processes the
ActionEvent
on the two
buttons. When you click the
OK
button, the message “OK button clicked” is displayed. When
you click the
Cancel
button, the message “Cancel button clicked” is displayed, as shown in
Figure 15.2.
L
ISTING
15.1
HandleEvent.java
1
import
javafx.application.Application;
2
import
javafx.geometry.Pos;
3
import
javafx.scene.Scene;
4
import
javafx.scene.control.Button;
5
import
javafx.scene.layout.HBox;
6
import
javafx.stage.Stage;
7
import
javafx.event.ActionEvent;
8
import
javafx.event.EventHandler;
9
10
public class
HandleEvent
extends
Application {
11 @Override
// Override the start method in the Application class
12
public void
start(Stage primaryStage) {
13
// Create a pane and set its properties
14 HBox pane =
new
HBox(
10
);
15 pane.setAlignment(Pos.CENTER);
16 Button btOK =
new
Button(
"OK"
);
17 Button btCancel =
new
Button(
"Cancel"
);
18 OKHandlerClass handler1 =
new
OKHandlerClass();
19 btOK.setOnAction(handler1);
20 CancelHandlerClass handler2 =
new
CancelHandlerClass();
21 btCancel.setOnAction(handler2);
22 pane.getChildren().addAll(btOK, btCancel);
23
24
// Create a scene and place it in the stage
25 Scene scene =
new
Scene(pane);
26 primaryStage.setTitle(
"HandleEvent"
);
// Set the stage title
27 primaryStage.setScene(scene);
// Place the scene in the stage
28 primaryStage.show();
// Display the stage
29 }
30 }
31
32
class
OKHandlerClass
implements
EventHandler<ActionEvent> {
33 @Override
34
public void
handle(ActionEvent e) {
35 System.out.println(
"OK button clicked"
);
36 }
37 }
38
39
class
CancelHandlerClass
implements
EventHandler<ActionEvent> {
40 @Override
41
public void
handle(ActionEvent e) {
42 System.out.println(
"Cancel button clicked"
);
43 }
44 }
create handler
register handler
create handler
register handler
handler class
handle event
handler class
handle event
Two handler classes are defined in lines 32-44. Each handler class implements
EventHandler<ActionEvent>
to process
ActionEvent
. The object
handler1
is an
instance of
OKHandlerClass
(line 18), which is registered with the button
btOK
(line
19). When the
OK
button is clicked, the
handle(ActionEvent)
method (line 34) in
Search WWH ::
Custom Search