Java Reference
In-Depth Information
key-released events,
getCode()
returns the value as defined in the table,
getText()
returns
a string that describes the key code, and
getCharacter()
returns an empty string. For the
key-typed event,
getCode()
returns
UNDEFINED
and
getCharacter()
returns the Unicode
character or a sequence of characters associated with the key-typed event.
key code
T
ABLE
15.2
KeyCode Constants
Constant
Description
Constant
Description
HOME
The Home key
CONTROL
The Control key
The End key
END
SHIFT
The Shift key
PAGE_UP
The Page Up key
BACK_SPACE
The Backspace key
PAGE_DOWN
The Page Down key
The Caps Lock key
CAPS
UP
The up-arrow key
NUM_LOCK
The Num Lock key
The down-arrow key
DOWN
ENTER
The Enter key
LEFT
The left-arrow key
UNDEFINED
The
keyCode
unknown
RIGHT
The right-arrow key
F1
to
F12
The function keys from F1 to F12
ESCAPE
The Esc key
0
to
9
The number keys from 0 to 9
The Tab key
TAB
A
to
Z
The letter keys from A to Z
The program in ListingĀ 15.8 displays a user-input character. The user can move the char-
acter up, down, left, and right, using the up, down, left, and right arrow keys. FigureĀ 15.13
contains a sample run of the program.
F
IGURE
15.13
The program responds to key events by displaying a character and moving it
up, down, left, or right.
L
ISTING
15.8
KeyEventDemo.java
1
import
javafx.application.Application;
2
import
javafx.scene.Scene;
3
import
javafx.scene.layout.Pane;
4
import
javafx.scene.text.Text;
5
import
javafx.stage.Stage;
6
7
public class
KeyEventDemo
extends
Application {
8 @Override
// Override the start method in the Application class
9
public void
start(Stage primaryStage) {
10
// Create a pane and set its properties
11 Pane pane =
new
Pane();
12 Text text =
new
Text(
20
,
20
,
"A"
);
13
14 pane.getChildren().add(text);
15 text.setOnKeyPressed(e -> {
16
create a pane
register handler
get the key pressed
move a character
switch
(e.getCode()) {
17
case
DOWN: text.setY(text.getY() +
10
);
break
;
18
case
UP: text.setY(text.getY() -
10
);
break
;
19
case
LEFT: text.setX(text.getX() -
10
);
break
;
20
case
RIGHT: text.setX(text.getX() +
10
);
break
;
Search WWH ::
Custom Search