javafx - 如何在 javafx 中借助键盘移动对象(形状)?
问题描述
我正在尝试构建一个 JavaFX 应用程序,在该应用程序中,我无法借助控制按钮在键盘的帮助下移动矩形,但它工作正常,但使用 keyevent 处理程序似乎甚至没有调用该函数。这是我的控制器类代码请给一些建议对不起语言不方便我实际上不知道如何提问谢谢
package sample;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.scene.shape.Shape3D;
import javafx.util.Duration;
import java.awt.*;
import java.net.URL;
import java.util.ResourceBundle;
import static javafx.scene.paint.Color.*;
public class Controller implements Initializable {
public Circle circle;
public Button b1;
public Button b2;
public Rectangle rectangle;
public Pane pane;
double dx = 4;
double dy = 4;
int count = 0;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
KeyFrame k = new KeyFrame(Duration.millis(100),
e - > {
circle.setLayoutX(circle.getLayoutX() + dx);
circle.setLayoutY(circle.getLayoutY() + dy);
if (circle.getLayoutX() < 30 | circle.getLayoutX() >= 600) {
dx = -dx;
}
if (circle.getLayoutY() < 30 | circle.getLayoutY() >= 400) {
dy = -dy;
}
//condition for collision with rectangle
Shape intersect = Shape.intersect(circle, rectangle);
if (intersect.getBoundsInParent().getWidth() != -1) {
dy = -dy;
}
}
);
Timeline t = new Timeline(k);
t.setCycleCount(Timeline.INDEFINITE);
t.play();
}
public void move(KeyEvent keyEvent) {
switch (keyEvent.getCode()) {
case A:
rectangle.setX(rectangle.getX() + 10);
break;
case B:
rectangle.setX(rectangle.getX() + 10);
break;
}
}
}
解决方案
尝试..
public void move(KeyEvent keyEvent) {
switch (keyEvent.getCode()) {
case A:
Platform.runLater(()->rectangle.setX(rectangle.getX() + 10));
break;
case B:
Platform.runLater(()->rectangle.setX(rectangle.getX() + 10));
break;
}
}
推荐阅读
- c - 打印节标题的精灵名称
- css - chrome 上的 CSS 背景过滤器比 safari 上的 -webkit-backdrop-filter 慢得多
- python - 如何使用python从postgresql中选择没有[(100),]的100这样的数据?
- validation - 如何解决不允许谓词(封闭形状)验证错误
- uipath - UiPath - 问题在字符串周围嵌入双引号
- reactjs - 如何动态显示反应组件
- c# - 带参数调用类时的C#反射性能比较
- r - 分别从每列中删除异常值 (3*IQR)
- r - R 中 imputeTS 的 na_kalman() 问题
- python - 我的 anaconda 导航器中没有 altair 包