问题
I am trying to make a simple program in Java using JavaFx to set the start and end point of the line object with Arrow Keys. Basically, the idea is to make line like snack with pressing the Arrow Keys. I used the setOnPressedKey event but it doesn't work, but when I remove the event and run the program the setStartX and setStartY and so on works.
Line line = new Line();
line.setStroke(Color.BLACK);
line.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP) {
line.setStartX(line.getEndX() + 0);
line.setStartY(line.getEndY() + 15);
}
});
layout.getChildren().add(line);
回答1:
You're adding an event on a component that doesn't request focus.
Set the event and focus on the root component.
Line line = new Line();
line.setStroke(Color.BLACK);
layout.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP) {
line.setStartX(line.getEndX() + 0);
line.setStartY(line.getEndY() + 15);
}
});
layout.getChildren().add(line);
layout.requestFocus();
来源:https://stackoverflow.com/questions/35734989/how-to-change-the-start-and-end-point-of-line-using-arrow-keys-in-javafx