Question

I'm using this example for implementing a custom DnD. I'd like to make my own DragImage and set it but this example doesn't use transfer handler. Where should I set the dragImage then?

I'm implementing the DnD for a compound component including a JPanel having more components and this example and also my code works excellent and I only need to have somewhere for set a dynamic DragImage for it. The drag image isn't fixed and it is generated after the drag begins as I have described here in another question[question].


Note: I add this info to explain more tentatives I made:

My mad transferHandler:

TransferHandler transferHandler = new TransferHandler(){
    private static final long serialVersionUID = 5071745666227627589L;

    @Override
    public boolean canImport(TransferSupport support) {
        boolean res = super.canImport(support);

        return res;
    }

    @Override
    public Icon getVisualRepresentation(Transferable t) {
    //  return super.getVisualRepresentation(t);
        return new ImageIcon(getDragImage());
    }

    @Override
    public Point getDragImageOffset() {
        return new Point(0, 0);
    }

    @Override
    public int getSourceActions(JComponent c) {
        int res = super.getSourceActions(c);
        setDragImage(getDragImage());
        return res;
    }

    @Override
    public boolean importData(TransferSupport support) {
        boolean res = super.importData(support);
        setDragImage(getDragImage());
        return res;
    }




    @Override
    public void setDragImage(Image img) {
        super.setDragImage(img);
    }

    @Override
    public Image getDragImage() {
        BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        printAll(g);
        g.dispose();                
        //setDragImage(image);
        return image;
    }

};

setTransferHandler(transferHandler);

And I tried to solve the problem chaning the cursor in dragGestureRecognized, it changes the gesture to a miniature image of the component but the image is so tiny. As tiny as the cursor. Setting cursor to null didn't work neither.

public void dragGestureRecognized(DragGestureEvent dge) {
    //Cursor cursor = DragSource.DefaultCopyDrop;
    Cursor c;
    c = Toolkit.getDefaultToolkit().createCustomCursor(jiJPanel.getTransferHandler().getDragImage(), new Point(0,0), "");
    dge.startDrag(c, new TransferableQuadrate(qi));
}

};

Was it helpful?

Solution

Maybe this will help? I had this old code lying around and I just added the one line of code to invoke the setDragImage() method in the ComponentHandler class. It uses the Screen Image class to create a image of the component you are moving. I didn't scale the image or anything so you get the whole component.

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.text.*;
import java.io.*;

public class DragComponent extends JPanel
{
//  public final static DataFlavor COMPONENT_FLAVOR = new DataFlavor(Component[].class, "Component Array");
    public static DataFlavor COMPONENT_FLAVOR;

    public DragComponent()
    {
        try
        {
            COMPONENT_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=\"" + Component[].class.getName() + "\"");
        }
        catch(Exception e)
        {
            System.out.println(e);
        }

        setLayout(null);
        setTransferHandler( new PanelHandler() );

        MouseListener listener = new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent e)
            {
                JComponent c = (JComponent) e.getSource();
                TransferHandler handler = c.getTransferHandler();
                handler.exportAsDrag(c, e, TransferHandler.MOVE);
            }
        };

        TransferHandler handler = new ComponentHandler();

        for (int i = 0; i < 5; i++)
        {
            JLabel label = new JLabel("Label " + i);
            label.setSize( label.getPreferredSize() );
            label.setLocation(30 * (i+1), 30 * (i+1));
            label.addMouseListener( listener );
            label.setTransferHandler( handler );
            add( label );
        }

        JPanel panel = new JPanel();
        panel.add( new JLabel("one") );
        panel.add( new JButton("two") );
        panel.setLocation(0, 180);
        panel.setSize( panel.getPreferredSize() );
        panel.addMouseListener( listener );
        panel.setTransferHandler( handler );
        add(panel);

    }

    private static void createAndShowUI()
    {
        DragComponent north = new DragComponent();
        north.setBackground(Color.RED);
        north.setPreferredSize( new Dimension(200, 200) );

        DragComponent south = new DragComponent();
        south.setBackground(Color.YELLOW);
        south.setPreferredSize( new Dimension(200, 200) );

        JFrame frame = new JFrame("DragComponent");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(north, BorderLayout.NORTH);
        frame.add(south, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

class ComponentHandler extends TransferHandler
{
    @Override
    public int getSourceActions(JComponent c)
    {
        setDragImage( ScreenImage.createImage(c) );

        return MOVE;
    }

    @Override
    public Transferable createTransferable(final JComponent c)
    {
        return new Transferable()
        {
            @Override
            public Object getTransferData(DataFlavor flavor)
            {
                Component[] components = new Component[1];
                components[0] = c;
                return components;
            }

            @Override
            public DataFlavor[] getTransferDataFlavors()
            {
                DataFlavor[] flavors = new DataFlavor[1];
                flavors[0] = DragComponent.COMPONENT_FLAVOR;
                return flavors;
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor)
            {
                return flavor.equals(DragComponent.COMPONENT_FLAVOR);
            }
        };
    }

    @Override
    public void exportDone(JComponent c, Transferable t, int action)
    {
        System.out.println(c.getBounds());
    }
}

class PanelHandler extends TransferHandler
{
    @Override
    public boolean canImport(TransferSupport support)
    {
        if (!support.isDrop())
        {
            return false;
        }

        boolean canImport = support.isDataFlavorSupported(DragComponent.COMPONENT_FLAVOR);
        return canImport;
    }

    @Override
    public boolean importData(TransferSupport support)
    {
        if (!canImport(support))
        {
            return false;
        }

        Component[] components;

        try
        {
            components = (Component[])support.getTransferable().getTransferData(DragComponent.COMPONENT_FLAVOR);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

        Component component = components[0];
        System.out.println(component.getClass());
        Container container = (Container)support.getComponent();
        container.add(component);
//      container.revalidate();
//      container.repaint();
        container.getParent().revalidate();
        container.getParent().repaint();

//      JLabel label = (JLabel)component;
        DropLocation location = support.getDropLocation();
//      System.out.println(label.getText() + " + " + location.getDropPoint());
        component.setLocation( location.getDropPoint() );

        return true;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top