我目前正在学习 Java,并正在使用 Java FX 进行事件驱动编程。该程序制作一个圆圈,并通过几种不同的方法(按钮、鼠标按钮、向上和向下箭头)增加其大小。
按钮和鼠标单击工作正常,但向上和向下箭头不行。似乎当我按下它们时,没有收到任何 KeyCodes。我尝试过将其更改为其他键,效果很好。
我实际上从书中复制了这个程序来练习,它与我的代码相同......
我使用的是 MacBook Pro 18,运行 Mojave 10.14.5。 Java 10,IntelliJ 社区版 2019.1。
代码如下,如有帮助,我们将不胜感激。
package testing2;
import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseButton; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage;
public class ControlCircleWithMouseAndKey extends Application {
private CirclePane circlePane = new CirclePane();
@Override
public void start(Stage primaryStage) {
//hold 2 buttons in an Hbos
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
Button btEnlarge = new Button("Enlarge");
Button btShrink = new Button("Shrink");
hBox.getChildren().addAll(btEnlarge, btShrink);
//Create and register button click handlers
btEnlarge.setOnAction(e -> circlePane.enlarge());
btShrink.setOnAction(e -> circlePane.shrink());
BorderPane borderPane = new BorderPane();
borderPane.setCenter(circlePane);
borderPane.setBottom(hBox);
borderPane.setAlignment(hBox, Pos.CENTER);
Scene scene = new Scene(borderPane, 200, 200);
primaryStage.setTitle("Change Circle");
primaryStage.setScene(scene);
primaryStage.show();
//Register the mouse clicks enlarge and shrink
circlePane.setOnMouseClicked(e -> {
if (e.getButton() == MouseButton.PRIMARY) {
circlePane.enlarge();
} else if (e.getButton() == MouseButton.SECONDARY) {
circlePane.shrink();
}
});
//Register keys to englarge and shrink
scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP) {
circlePane.enlarge();
} else if (e.getCode() == KeyCode.DOWN) {
circlePane.shrink();
} else {
System.out.println(e.getCode());
}
});
} }
class CirclePane extends StackPane {
private Circle circle = new Circle(50);
public CirclePane() {
getChildren().add(circle);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
}
public void enlarge() {
circle.setRadius(circle.getRadius() + 2);
}
public void shrink() {
circle.setRadius(circle.getRadius() > 2 ? circle.getRadius() - 1 : circle.getRadius());
} }
最佳答案
您已使用“场景”来注册按键。难道不应该是“borderPane”(我猜这一切都取决于焦点)?
关于按下向上和向下箭头时,Java FX 无法识别 KeyCode.UP 或 KeyCode.Down (MacBook Pro 18 - Mojave 10.14.5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56200192/