Java Reference
In-Depth Information
rightPaddle.setOnMouseDragged(me -> {
double dragY = me.getSceneY() - rightPaddleDragAnchorY;
rightPaddleY.setValue(initRightPaddleTranslateY + dragY);
});
...code omitted...
rightPaddle.translateYProperty().bind(rightPaddleY);
Note that in this ZenPong example, we're dragging the paddles only vertically, not horizontally Therefore, the
code snippet only deals with dragging on the y axis. After creating the paddle at the initial location, we register event
handlers for MousePressed and MouseDragged events. The latter manipulates the rightPaddleY property, which is
used for translating the paddle along the y axis. Properties and bindings will be explained in detail in Chapter 4.
Giving Keyboard Input Focus to a Node
For a node to receive key events, it has to have keyboard focus. This is accomplished in the ZenPong example by doing
these two things, as shown in the snippet that follows from Listing 2-8:
focusTraversable property of the Group node. This allows the node to
accept keyboard focus.
Assigning true to the
requestFocus() method of the Group node (referred to by the pongComponents
variable). This requests that the node obtain focus.
Calling the
You cannot directly set the value of the focused property of a Stage . Consulting the api docs also reveals that you
cannot set the value of the focused property of a Node (e.g., the Group that we're discussing now). however, as discussed
in the second point just mentioned, you can call requestFocus() on the node, which if granted (and focusTraversable
is true) sets the focused property to true. By the way, Stage doesn't have a requestFocus() method, but it does have a
toFront() method, which should give it keyboard focus.
Tip
...code omitted...
pongComponents.setFocusTraversable(true);
pongComponents.setOnKeyPressed(k -> {
if (k.getCode() == KeyCode.SPACE
&& pongAnimation.statusProperty()
.equals(Animation.Status.STOPPED)) {
rightPaddleY.setValue(rightPaddleY.getValue() - 6);
} else if (k.getCode() == KeyCode.L
&& !rightPaddle.getBoundsInParent().intersects(topWall.getBoundsInLocal())) {
rightPaddleY.setValue(rightPaddleY.getValue() - 6);
} else if (k.getCode() == KeyCode.COMMA
&& !rightPaddle.getBoundsInParent().intersects(bottomWall.getBoundsInLocal())) {
rightPaddleY.setValue(rightPaddleY.getValue() + 6);
} else if (k.getCode() == KeyCode.A
&& !leftPaddle.getBoundsInParent().intersects(topWall.getBoundsInLocal())) {
leftPaddleY.setValue(leftPaddleY.getValue() - 6);
 
 
Search WWH ::




Custom Search