Java Reference
In-Depth Information
21
default :
22
if (Character.isLetterOrDigit(e.getText().charAt( 0 )))
23
text.setText(e.getText());
set a new character
24 }
25 });
26
27 // Create a scene and place it in the stage
28 Scene scene = new Scene(pane);
29 primaryStage.setTitle( "KeyEventDemo" ); // Set the stage title
30 primaryStage.setScene(scene); // Place the scene in the stage
31 primaryStage.show(); // Display the stage
32
33
text.requestFocus(); // text is focused to receive key input
request focus on text
34 }
35 }
The program creates a pane (line 11), creates a text (line 12), and places the text into the pane
(line 14). The text registers the handler for the key-pressed event in lines 15-25. When a key is
pressed, the handler is invoked. The program uses e.getCode() (line 16) to obtain the key code
and e.getText() (line 23) to get the character for the key. When a nonarrow key is pressed, the
character is displayed (lines 22 and 23). When an arrow key is pressed, the character moves in the
direction indicated by the arrow key (lines 17-20). Note that in a switch statement for an enum
type value, the cases are for the enum constants (lines 16-24). The constants are unqualified. For
example, using KeyCode.DOWN in the case clause would be wrong (see Appendix I).
Only a focused node can receive KeyEvent . Invoking requestFocus() on text enables
text to receive key input (line 33). This method must be invoked after the stage is displayed.
We can now add more control for our ControlCircle example in ListingĀ 15.3 to increase/
decrease the circle radius by clicking the left/right mouse button or by pressing the U and D
keys. The new program is given in ListingĀ 15.9.
requestFocus()
L ISTING 15.9
ControlCircleWithMouseAndKey.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.input.KeyCode;
6 import javafx.scene.input.MouseButton;
7 import javafx.scene.layout.HBox;
8 import javafx.scene.layout.BorderPane;
9 import javafx.stage.Stage;
10
11 public class ControlCircleWithMouseAndKey extends Application {
12
private CirclePane circlePane = new CirclePane();
13
14 @Override // Override the start method in the Application class
15 public void start(Stage primaryStage) {
16 // Hold two buttons in an HBox
17 HBox hBox = new HBox();
18 hBox.setSpacing( 10 );
19 hBox.setAlignment(Pos.CENTER);
20 Button btEnlarge = new Button( "Enlarge" );
21 Button btShrink = new Button( "Shrink" );
22 hBox.getChildren().add(btEnlarge);
23 hBox.getChildren().add(btShrink);
24
25 // Create and register the handler
26 btEnlarge.setOnAction(e -> circlePane.enlarge());
27 btShrink.setOnAction(e -> circlePane.shrink());
button handler
 
 
Search WWH ::




Custom Search