我想暫停PathTransition並使用鍵盤鍵重新啓動P. 而且我正嘗試使用UP/DOWN鍵增加和減小動畫速度。onKeyPressed函數不能在JavaFX中工作
但是當我運行代碼時,這些按鈕似乎不起作用。我究竟做錯了什麼?
package exercise_15_29;
import javafx.animation.Animation;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polygon;
import javafx.scene.input.KeyCode;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Exercise_15_29 extends Application {
Group car = new Group();
Circle wheel1 = new Circle(15,95,5);
Circle wheel2 = new Circle(35,95,5);
Polygon body1 = new Polygon();
Rectangle body2 = new Rectangle(0.0,80.0,50,10);
Line path = new Line(0,90,500,90);
int speed = 4000;
boolean play = true;
@Override
public void start(Stage primaryStage) {
body1.getPoints().addAll(new Double[]{
10.0, 80.0,
20.0, 70.0,
30.0, 70.0,
40.0, 80.0
});
body1.setFill(Color.BLUE);
body2.setFill(Color.SKYBLUE);
path.setVisible (false);
car.getChildren().addAll(wheel1,wheel2,body1,body2);
PathTransition pt = new PathTransition();
pt.setDuration(Duration.millis(speed));
pt.setPath(path);
pt.setNode(car);
pt.setCycleCount(Timeline.INDEFINITE);
pt.setAutoReverse(false);
pt.play();
Pane root = new Pane();
root.getChildren().add(car);
root.getChildren().add(path);
Scene scene = new Scene(root, 500, 100);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
root.setOnKeyTyped(e -> {
if(e.getCode() == KeyCode.P) {
if(play == true)
pt.stop();
else
pt.play();
play = !play;
}
});
root.setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.UP)
pt.setDuration(Duration.millis(++speed));
else if(e.getCode() == KeyCode.DOWN)
pt.setDuration(Duration.millis(--speed));
});
}
public static void main(String[] args) {
launch(args);
}
}
不知道爲什麼,但它似乎工作,如果你在'場景'而不是'窗格'上設置事件偵聽器。可能與焦點模型有關... – Itai