概要

JList間でのドラッグ&ドロップによるアイテムの移動や並べ替えを行います。

サンプルコード

class ListItemTransferHandler extends TransferHandler {
  protected final DataFlavor localObjectFlavor;
  protected JList<?> source;
  protected int[] indices;
  protected int addIndex = -1;
  protected int addCount;

  protected ListItemTransferHandler() {
    super();
    localObjectFlavor = new DataFlavor(List.class, "List of items");
  }
  @Override protected Transferable createTransferable(JComponent c) {
    source = (JList<?>) c;
    indices = source.getSelectedIndices();
    List<?> transferedObjects = source.getSelectedValuesList();
    return new Transferable() {
      @Override public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[] {localObjectFlavor};
      }
      @Override public boolean isDataFlavorSupported(DataFlavor flavor) {
        return Objects.equals(localObjectFlavor, flavor);
      }
      @Override public Object getTransferData(DataFlavor flavor)
          throws UnsupportedFlavorException, IOException {
        if (isDataFlavorSupported(flavor)) {
          return transferedObjects;
        } else {
          throw new UnsupportedFlavorException(flavor);
        }
      }
    };
  }
  @Override public boolean canImport(TransferHandler.TransferSupport info) {
    return info.isDrop() && info.isDataFlavorSupported(localObjectFlavor);
  }
  @Override public int getSourceActions(JComponent c) {
    return TransferHandler.MOVE;
  }
  @SuppressWarnings("unchecked")
  @Override public boolean importData(TransferHandler.TransferSupport info) {
    TransferHandler.DropLocation tdl = info.getDropLocation();
    if (!canImport(info) || !(tdl instanceof JList.DropLocation)) {
      return false;
    }
    JList.DropLocation dl = (JList.DropLocation) tdl;
    JList<?> target = (JList<?>) info.getComponent();
    DefaultListModel listModel = (DefaultListModel) target.getModel();
    int max = listModel.getSize();
    int index = dl.getIndex();
    index = index < 0 ? max : index;
    index = Math.min(index, max);
    addIndex = index;
    try {
      List<?> values = (List<?>) info.getTransferable().getTransferData(
        localObjectFlavor);
      for (Object o : values) {
        int i = index++;
        listModel.add(i, o);
        target.addSelectionInterval(i, i);
      }
      // ---->
      addCount = target.equals(source) ? values.size() : 0;
      // <----
      return true;
    } catch (UnsupportedFlavorException | IOException ex) {
      ex.printStackTrace();
    }
    return false;
  }
  // ...
view all

解説

上記のサンプルでは、一つのJList内でのアイテムの並べ替えを行うTransferHandlerを使ったJListのドラッグ&ドロップによる並べ替えを元にListItemTransferHandlerを作成し、JList間でのアイテム移動も可能にしています。

参考リンク

コメント