0
votes

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.

1
I believe you have to first capture the 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 probably onDragEntered, but you have to specify what drag types the node allows.Itai
A lot of the Oracle examples assume you're starting the drag process from within another JavaFX node (which doesn't help in this case). I'll try capturing onDragEntered and see if that helps. Thanks!Michael Hillman

1 Answers

0
votes

After some testing on colleagues screens, this looks like it could be an issue with JavaFX on 4K monitors. This example (and others found online) work as intended on 1080p monitors, but not on 4K ones.

I guess I'll have to test this feature in 1080p and hope my users don't have 4K screens.