1

I want text fields to be able to handle a drop of a file from the finder.

This seems to be ignored on Mac OS X using JavaFX 8. I can't see any problems with the code, can you?

Only "Entered!" gets printed. "Dropped!" never gets printed.

...
txtSource = (TextField)scene.lookup("#txtSource");
txtSource.setOnDragEntered(this::handleEnter);
txtSource.setOnDragDropped(this::handleDrop);
...

public void handleEnter(DragEvent event) {
    System.out.println("Entered!");
    event.acceptTransferModes(TransferMode.ANY);
    event.consume();
}

public void handleDrop(DragEvent event) {
    System.out.println("Dropped!");

    Dragboard db = event.getDragboard();
    boolean success = false;
    if (db.hasFiles()) {
        File f = db.getFiles().get(0);
        TextField t = (TextField)event.getAcceptingObject();
        t.setText(f.getAbsolutePath());
        success = true;
    }
    /* let the source know whether the string was successfully 
     * transferred and used */
    event.setDropCompleted(success);
    event.consume();
}

1 Answer 1

0

For some reason not clear to me, you need to accept the transfer mode in a dragOver handler, not a dragEntered handler:

txtSource.setOnDragOver(this::handleEnter);
// txtSource.setOnDragEntered(this::handleEnter);
2
  • Thanks. That worked. Strange. I got my original code from tutorial examples. Is this an OS X only quirk? BTW Also my event.getAcceptingObject() should have been event.getGestureTarget() to get the text field.
    – John Baker
    Dec 7, 2015 at 15:12
  • No idea on other platforms: I only have a mac to test on. FWIW I would explicitly pass the text field (or make it an instance variable): txtSource.setOnDragDropped(e -> handleDragDrop(e, txtSource)); and private void handleDragDrop(DragEvent e, TextField t) { ... }.
    – James_D
    Dec 7, 2015 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.