I have added to one of the JLists in my java program a Drag and Drop transfer handler. I added a method to this JList so as to have a nice ghost image effect of the selected values I am dragging. This effect works just fine until I add the transfer handler :
In that case, this method :
myList.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent evt) {
System.out.println("Dragging");
}
});
from :
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.io.IOException;
import java.util.ArrayList;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataHandler;
import javax.swing.*;
class ListExample extends JFrame
{
private JPanel topPanel;
private JList myList;
public ListExample()
{
setSize(300, 100 );
topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
String listData[] =
{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
};
myList = new JList(listData);
myList.setDragEnabled(true);
ListItemTransferHandler handler = new ListItemTransferHandler();
myList.setTransferHandler(handler);
topPanel.add( myList, BorderLayout.CENTER );
myList.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent evt) {
System.out.println("Dragging");
}
});
}
public static void main( String args[] )
{
ListExample mainFrame = new ListExample();
mainFrame.setVisible(true );
}
class ListItemTransferHandler extends TransferHandler {
private final DataFlavor localObjectFlavor;
private Object[] transferedObjects = null;
public ListItemTransferHandler() {
localObjectFlavor = new ActivationDataFlavor(Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items");
}
private JList source = null;
@SuppressWarnings("deprecation")
@Override protected Transferable createTransferable(JComponent c) {
source = (JList) c;
transferedObjects = source.getSelectedValues();
return new DataHandler(transferedObjects, localObjectFlavor.getMimeType());
}
@Override public boolean canImport(TransferSupport info) {
return true;
}
@Override public int getSourceActions(JComponent c) {
return MOVE; //TransferHandler.COPY_OR_MOVE;
}
}
}
gets called once or twice as I begin to drag, but as soon as I get a few pixels away, the source selection changes colour and my dragmouse listener is no longer called, and the ghost image stays nearby the source of the dragged object. However, I can still drag my selected cells and drop them where I want. It's just that the ghost image doesn't follow all the way. I am obviously missing something important here but since it is a rather specific problem I couldn't find help anywhere, so suggestions would be appreciated.