Google Tag Manager

2010/08/09

aterai

Drag and Drop between JLists

Code

class ListItemTransferHandler extends TransferHandler {
  private JList source = null;
  @Override protected Transferable createTransferable(JComponent c) {
    source = (JList) c;
    indices = source.getSelectedIndices();
    transferedObjects = source.getSelectedValues();
    return new DataHandler(transferedObjects, localObjectFlavor.getMimeType());
  }
  @Override public boolean importData(TransferHandler.TransferSupport info) {
    if (!canImport(info)) return false;
    JList target = (JList)info.getComponent();
    JList.DropLocation dl = (JList.DropLocation)info.getDropLocation();
    DefaultListModel listModel = (DefaultListModel)target.getModel();
    int index = dl.getIndex();
    int max = listModel.getSize();
    if(index < 0 || index > max) index = max;
    addIndex = index;
    try{
      Object[] values = (Object[])info.getTransferable().getTransferData(localObjectFlavor);
      for(int i=0;i < values.length;i++) {
        int idx = index++;
        listModel.add(idx, values[i]);
        target.addSelectionInterval(idx, idx);
      }
      addCount = (target==source)? values.length : 0;
      return true;
    }catch(UnsupportedFlavorException ufe) {
      ufe.printStackTrace();
    }catch(java.io.IOException ioe) {
      ioe.printStackTrace();
    }
    return false;
  }
//......

References

2 comments: