
Reorder a JList with Drag-and-Drop #17
Chapter 2, Lists and Combos
|
85
HACK
correct drop index will be one less than you’d expect. After all, by deleting it
from the list, everything after its old location has now moved up one index.
All of this is handled by the
drop( )
method, shown in Example 2-16.
Finally, you need to call
dropComplete( ) to tell the DropTargetDropEvent
whether the drag-and-drop succeeded.
Example 2-16. Handling the drop on the reorderable JList
public void drop (DropTargetDropEvent dtde) {
System.out.println ("drop( )!");
if (dtde.getSource( ) != dropTarget) {
System.out.println ("rejecting for bad source (" +
dtde.getSource().getClass().getName( ) + ")");
dtde.rejectDrop( );
return;
}
Point dropPoint = dtde.getLocation( );
int index = locationToIndex (dropPoint);
System.out.println ("drop index is " + index);
boolean dropped = false;
try {
if ((index == -1) || (index == draggedIndex)) {
System.out.println ("dropped onto self");
dtde.rejectDrop( );
return;
}
dtde.acceptDrop (DnDConstants.ACTION_MOVE);
System.out.println ("accepted");
Object dragged =
dtde.getTransferable( ).getTransferData(localObjectFlavor);
// move items - note that indicies for insert will
// change if [removed] source was before target
System.out.println ("drop " + draggedIndex + " to " + index);
boolean sourceBeforeTarget = (draggedIndex < index);
System.out.println ("source is" +
(sourceBeforeTarget ...