gpt4 book ai didi

java - onDragOver 不会发生(在 JavaFX 中)

转载 作者:行者123 更新时间:2023-12-01 21:16:00 24 4
gpt4 key购买 nike

为什么下面的示例中没有发生 onDragOver 事件?

如何实现最简单的拖动行为,即没有剪贴板的东西?

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.input.DragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.paint.*;
import javafx.stage.Stage;

public class DragTry extends Application {

private Point2D dragVector = null;

@Override
public void start(Stage primaryStage) throws Exception {

Pane root = new Pane();

Pane node = new Pane();
node.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, javafx.geometry.Insets.EMPTY)));
node.setPrefWidth(100);
node.setPrefHeight(50);
node.setTranslateX(200);
node.setTranslateY(200);

node.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("odDragDetected");

double x = event.getX();
double y = event.getY();
x -= node.getTranslateX();
y -= node.getTranslateY();
dragVector = new Point2D(x, y);
node.startFullDrag();
}
});

node.setOnDragOver(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
System.out.println("onDragOver");

double x = event.getX();
double y = event.getY();
x += dragVector.getX();
y += dragVector.getY();
node.setTranslateX(x);
node.setTranslateY(y);
}
});

node.setOnDragDone(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
dragVector = null;
}
});

root.getChildren().add(node);

Scene scene = new Scene(root, 800, 600);

primaryStage.setScene(scene);
primaryStage.setTitle("DragTry");
primaryStage.show();
}


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

最佳答案

首先,您需要调用startDragAndDrop,而不是startFullDragdocumentation for MouseEvent 中描述了不同的拖动模式。 。此外,拖放 API 的一个烦人的部分是,除非您向拖板添加某些内容,否则不会激活拖动:

  node.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("odDragDetected");

double x = event.getX();
double y = event.getY();
x -= node.getTranslateX();
y -= node.getTranslateY();
dragVector = new Point2D(x, y);

Dragboard db = node.startDragAndDrop(TransferMode.COPY_OR_MOVE);
ClipboardContent cc = new ClipboardContent();
cc.putString("Something");
db.setContent(cc);
}
});

关于java - onDragOver 不会发生(在 JavaFX 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40074650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com