JavaFX drag and drop custom data
JavaFX has greatly simplified Drag and Drop over the mess that was in AWT and then given a zombified life through Swing.
To drag and drop custom data types, i.e. non string data, in Swing, you had to create a DataFlavor class with a MIME type. In JavaFX, all you have to do is create a simple DataFormat object.
1 |
DataFormat myformat = new DataFormat("some string that identifies your object"); |
And then use it like this in your setOnDragDetected handler.
1 2 3 4 5 6 |
Dragboard db = grandStaff.startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); //This is my class MIDITrack track = grandStaff.getMIDITrack(); content.put(midiTrackDataFormat, track); db.setContent(content); |
You may get this problem when putting your object on the Dragboard in OSX:
“…is not a valid UTI string. Cannot set data for an invalid UTI.”
Digging through my XCode documentation on the OSX pasteboard, I found that the format HAS to be the usual reverse domain name class name we’ve been using for years.
1 2 |
private static final DataFormat midiTrackDataFormat = new DataFormat( "com.rockhoppertech.music.midi.js.MIDITrack"); |
The thing is, the JavaFX documentation – and Oracle’s tutorial – makes no mention of this.
I hope this tidbit saves you some time.