Wednesday, November 23, 2011

Drag and Drop of complex custom objects in Java


There are a lot of ways to accomplish this task. Here I'll show the custom way, that intends to work in any kind of swing component with minimum changes.

Here we have two JPanels, one of them has a custom JLabel that holds an Animal object. When we drag the JLabel, we want to transfer copying the animal to the other JPanel.

Basically, to do DnD (drag and drop) we have to create a Drag source, a Drag Target and a Transferable object:



Acess the example code clicking above on the link.(Gist powered)
https://gist.github.com/840867



Note that, most of the time, you need to do more easy tasks with DnD, like transfering simple Strings between components. There are easier ways to do that with the Java Swing default DnD implementations. See the references.





References

  1. Zet Code. Accessed in 23 February 2011.
    Zet Code
  2. Java tutorials. Accessed in 23 February 2011.
    http://download.oracle.com/javase/tutorial/uiswing/dnd/intro.html

No comments:

Post a Comment