I doubt that this functionality can be useful for someone in 21st century. I’m sure no one else uses Swing now :) Anyway I got a business requirement to do that. I’ve been using Swing for 3 years, not so often and didn’t touch drag-and-drop in swing before. This task sounds pretty crazy at the beginning. I was sure that I can’t communicate in the Swing app with the outside world - I was wrong. First thing which I checked, I tried to drag a folder in project tree of IDEA and drop to the desktop and this worked. Next I started to google and found nothing which can help me with my task.
Here I started my experiments which produced following code.
To recognize drag-and-drop gestures here we have java.awt.dnd.DragSource. Let’s assume we need to have a draggable button on a frame.
If you try to drag the button your cursor will be shown as a draggable action happens. TransferData represents the way of data transfer. And it could be some thing like that:
getTransferDataFlavors method tells DragSource which type of data will be transferred here.
getTransferData method returns the data itself. As you see I used Gson to serialize my business object to json.
Here we go. The working example you can find in my github project with examples.