I'm attempting to create a feature that allows users to drag files from outside the application (say Windows explorer) into the JavaFX program. I can't seem to get my drag events to fire though, any thoughts?
Example code...
public class DragTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("DragTest");
Group root = new Group();
Scene scene = new Scene(root, 400, 400);
Label label = new Label("Drag files here!");
label.setStyle("-fx-background-color: skyblue;");
label.setPrefWidth(300);
label.setPrefHeight(100);
// On drag enter
label.setOnDragEntered((DragEvent event) -> {
System.out.println("DRAG ENTERED");
if (event.getGestureSource() != label) {
event.acceptTransferModes(TransferMode.ANY);
}
event.consume();
});
// On drag detected
label.setOnDragOver((DragEvent event) -> {
System.out.println("DRAG OVER");
if (event.getGestureSource() != label && event.getDragboard().hasFiles()) {
event.acceptTransferModes(TransferMode.ANY);
}
event.consume();
});
// On drag drop
label.setOnDragDropped((DragEvent event) -> {
System.out.println("DRAG DROP");
Dragboard db = event.getDragboard();
if (db.hasFiles()) {
label.setText(db.getFiles().size() + " files detected!");
} else {
label.setText("No dragged files detected");
}
event.setDropCompleted(true);
event.consume();
});
root.getChildren().add(label);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Edit: Captured onDragEntered() event, doesn't seem to fire at all.
onDragDetected
event, and there define what drag types are allowed. See: docs.oracle.com/javase/8/javafx/api/javafx/scene/… Edit: Err.. this is in case you want to start a drag from this node. Otherwise the correct place is probablyonDragEntered
, but you have to specify what drag types the node allows. – ItaionDragEntered
and see if that helps. Thanks! – Michael Hillman