Monday, July 17, 2006

Drag Images for Everyone...and we do mean Everyone

You may have seen Sun's tutorial on using Swing's built-in drag and drop support. One of the demos from the tutorial looks like this:



Today's demo puts a drag image on each of the displayed drag-enabled components, and does so without modifying the original jar file. It also does so without any special knowledge of the components that are drag enabled. (Web start doesn't let you reference a file on another host, so you'll have to trust me when I say the original jar is used unmodified).



A few sights to take in after you've checked that "Turn on Drag and Drop" checkbox.


  • Try a drag from each component.
  • Try dragging a multiple, discontiguous selection from each component.
  • Watch what happens when your drop is rejected.
  • Move the main window, and drag some more. Notice the nice images across both windows (the original main has simply been called twice).


Source Here.

The technique depends on all drag sources to use the default DragSource as the drag initiator. To date, all drags implemented within the JRE use the default, as do all the drag & drop examples I've seen on the web, so it always works in practice.

The global drag source listener technique used here could also be used to automatically switch the visible tab in a JTabbedPane, expand a node in a JTree, or even autoscroll components that don't implement Autoscroll. Watch for an upcoming article to address those options.

7 comments:

Anonymous said...

Very very cool!
Why not commit this to swinglabs, as well as some of your other goodies?

Anonymous said...

I tried download the sources but I get:

3. Error notes: File does not exist: /home/groups/a/ab/abbot/htdocs/demo/SwingDragImages-src.jar

technomage said...

It's there now, please try again.

Anonymous said...

Very nice,

I have done very little stuff with
drag and drop and perhaps this is
possible but.. when dragging something
over a JTabbedPane's tab I would like
it to open up this tab. Is this
possible in Swing DnD or would one
have to do custom tweaking?

technomage said...

See addendum to the article.

Anonymous said...

If tried it and it works pretty nice but I get excessive drag icon flickering. Any idea what the problem could be?

daljeet said...

the drag image does not work for applets ,please let me know what changes i can make to make it run for applets as well , i will really appreaciate the help. my email id is-> daljeet.gandhi"at"gmail.com