为什么 JavaFX 只接收一次鼠标事件?

Why does JavaFX only receive mouse events once?

我正在开发一个可以将 ImageView 拖放到场景中任意位置的应用程序。当我 运行 应用程序时,它在我第一次拖动 ImageView 时工作正常,但在我释放它后没有响应。

这是我的 FXML 控制器:

@FXML
private ImageView card;

@FXML
private void handleCardMousePressed(MouseEvent event) {
    System.out.println("Drag Entered");
    DropShadow dropShadow=new DropShadow();
    dropShadow.setColor(Color.rgb(18,139,237));
    dropShadow.setSpread(.48);
    card.setEffect(dropShadow);
    card.setMouseTransparent(true);
    event.consume();
}

@FXML
private void handleCardMouseDragged(MouseEvent event){
    System.out.println("In Drag");
    card.setLayoutX(event.getSceneX());
    card.setLayoutY(event.getSceneY());
    event.consume();
}
@FXML
private void handleCardMouseReleased(MouseEvent event){
    System.out.println("Exit Drag");
    card.setEffect(null);
    event.consume();
}

Video of What is Happening

不要在 handleMouseCardPressed 方法中将 mouseTransparent 设置为 true

如果您出于其他原因需要这样做(我不明白您为什么会这样做),那么在 handleCardMouseReleased(...) 中您需要将 mouseTransparent 设置回 false:

    card.setMouseTransparent(false);

完整示例:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class DragImageViewExample extends Application {

    private ImageView card;

    @Override
    public void start(Stage primaryStage) {
        Rectangle rect = new Rectangle(30, 30, Color.CORAL);
        card = new ImageView(rect.snapshot(null, null));

        card.setOnMousePressed(this::handleCardMousePressed);
        card.setOnMouseDragged(this::handleCardMouseDragged);
        card.setOnMouseReleased(this::handleCardMouseReleased);

        Pane pane = new Pane(card);
        Scene scene = new Scene(pane, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void handleCardMousePressed(MouseEvent event) {
        System.out.println("Drag Entered");
        DropShadow dropShadow=new DropShadow();
        dropShadow.setColor(Color.rgb(18,139,237));
        dropShadow.setSpread(.48);
        card.setEffect(dropShadow);
        event.consume();
    }

    private void handleCardMouseDragged(MouseEvent event){
        System.out.println("In Drag");
        card.setLayoutX(event.getSceneX());
        card.setLayoutY(event.getSceneY());
        event.consume();
    }

    private void handleCardMouseReleased(MouseEvent event){
        System.out.println("Exit Drag");
        card.setEffect(null);
        event.consume();
    }

    public static void main(String[] args) {
        launch(args);
    }
}