我正在开发一个应用程序,可以将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();
}
发生了什么的视频
不要在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);
}
}