create Transferable Object - Java Swing

Java examples for Swing:Drag and Drop

Description

create Transferable Object

Demo Code


//package com.java2s;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;

public class Main {
    public static Transferable createTransferable(final Object obj) {
        final String localObject = DataFlavor.javaJVMLocalObjectMimeType
                + ";class=" + obj.getClass().getCanonicalName();

        final DataFlavor flavor;

        try {//  w w w.j a v a 2s.c  o  m
            flavor = new DataFlavor(localObject);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        return new Transferable() {
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[] { flavor };
            }

            public boolean isDataFlavorSupported(DataFlavor oflavor) {
                if (oflavor.getRepresentationClass().isAssignableFrom(
                        obj.getClass()))
                    return true;
                return false;
            }

            public DataFlavor getDataFlavor() {
                return flavor;
            }

            public Object getTransferData(DataFlavor oflavor) {
                try {
                    if (isDataFlavorSupported(oflavor)) {
                        return obj;
                    } else {
                        return null;
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }

            }

        };
    }
}

Related Tutorials