Firstly, a warning: Sun’s official tutorial on 1.4 dnd is wrong, and presents source code that I know the author never tested because it could never have worked. In particular, the code in this section: http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html#customComp won’t work because it includes some methods from MouseListener, but the component neither implements that interface nor does it invoke addMouseListener. And the whole algorithm presented requires the MouseListener in order to execute.
Secondly, if you get to the point where you’re thinking “I can’t seem to implement the method they want me to implement that will encode the exported data as a Transferable” then you are correct: Some god-forsaken person designed this part so that it doesn’t tell you what x and y the mouse was at when it initiated the drag…so, any source Component with multiple internal pieces of data has no way of knowing what item in the list/tree/etc was dragged (hence JTree has to wait until something is selected, and then just re-use the last selection - this is one of the highly-voted-for bugs on the bug parade, and instead of faffing with selection mechanisms and “handler precedence” (the official reasons for taking 3 years not to fix it), it looks like they could just fix the API and it would then become relatively trivial to fix JTree).
It’s so stupid an omission you have to laugh (or else you’d cry :(),
[emote]wonders how long it’ll be before java has real drag-n-drop support[/emote]
Anyway… the best workaround I’ve seen is to be a bit non-object-oriented and have backdoors between your components so that they can sneakily share the information that the clever dnd API refuses to let them have. When you’re initiating DND in your source component, using a MouseMotionListener.mouseDragged method, calculate the item currently pointed to by the MouseEvent that started the drag, and save it into an instance variable. Then, when your TransferHandler is asked to generate a Transferable, it reads the aforementioned variable (either directly or indirectly via your component) to get a handle to the data which it can then wrap into the Transferable.
(if anyone’s got a better one, please let me know - and CC: it to the swing team, and just maybe they might use it to fix up JTree etc).
FYI, I’ve only belatedly sorted all this out because it’s only on my N-th attempt to use D-n-D that I got around to fully exercising the API and finally fully understanding what was really going on. All previous apps where I’ve used it I’ve beaten about the bush, and just hacked until it worked. I’m hoping this advice might help some people (since it looks like Sun won’t have the bugs sorted for some time to come yet; they need to re-think the API really. It’s also kind of tragic that one of their tutorials is a blank page, and the other wouldn’t execute if you tried).