Java – Constructing a DataFlavor for drag and drop of an array of java objects

drag and dropjavaswing

I want to implement drag and drop between two components within the same JVM. I'm passing an array of objects which are not serializable, so I'm trying to find the correct incantation of javaJVMLocalObjectMimeType to pass in. However, I keep getting an illegal argument exception.

As an example, if i have ExampleClass

Appending class parameters works:

    new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType+";class="+ExampleClass.class.getName());

But fails with an array type:

    new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType+";class="+ExampleClass[].class.getName());

which throws:

java.lang.IllegalArgumentException: failed to parse:application/x-java-jvm-local-objectref;class=[LExampleClass

Aargh! Drag&Drop in swing is such a complete mess!

Best Answer

Try this:

new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType +
               ";class=\""+ExampleClass.class.getName() + "\"");

Since the name of an array (e.g. "[Ljava.lang.Object;") has special characters, you have to quote the "class" parameter.