首页 > 解决方案 > 如何在 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;
        }
    }
}

标签: javafxevent-handling

解决方案


尝试..

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;
    }
}

推荐阅读