• title: JTableの行をドラッグ&ドロップ tags: [JTable, DragAndDrop] author: aterai pubdate: 2007-04-02T16:29:09+09:00 description: JTableの行をドラッグ&ドロップで入れ替えます。

概要

JTableの行をドラッグ&ドロップで入れ替えます。

サンプルコード

class DnDTable extends JTable implements DragGestureListener, Transferable {
  private static final String NAME = "test";
  private static final DataFlavor FLAVOR =
    new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);
  private static final Color LINE_COLOR = new Color(255, 100, 100);
  private final Rectangle2D targetLine = new Rectangle2D.Float();
  private int draggedIndex = -1;
  private int targetIndex  = -1;

  public DnDTable(TableModel model) {
    super(model);
    //DropTarget dropTarget =
    new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,
                   new CDropTargetListener(), true);
    //DragSource dragSource = new DragSource();
    new DragSource().createDefaultDragGestureRecognizer(
        (Component) this, DnDConstants.ACTION_COPY_OR_MOVE,
        (DragGestureListener) this);
  }
  @Override public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (targetIndex >= 0) {
      Graphics2D g2 = (Graphics2D) g.create();
      g2.setPaint(LINE_COLOR);
      g2.fill(targetLine);
      g2.dispose();
    }
  }
  private void initTargetLine(Point p) {
    Rectangle2D testArea = new Rectangle2D.Float();
    int cellHeight = getRowHeight();
    int lineWidht  = getWidth();
    int lineHeight = 2;
    int modelSize  = getRowCount();
    targetIndex = -1;
    for (int i = 0; i < modelSize; i++) {
      testArea.setRect(
          0, cellHeight * i - cellHeight / 2, lineWidht, cellHeight);
      if (testArea.contains(p)) {
        targetIndex = i;
        targetLine.setRect(0, i * cellHeight, lineWidht, lineHeight);
        break;
      }
    }
    if (targetIndex < 0) {
      targetIndex = modelSize;
      targetLine.setRect(
          0, targetIndex * cellHeight - lineHeight, lineWidht, lineHeight);
    }
  }

  // Interface: DragGestureListener
  @Override public void dragGestureRecognized(DragGestureEvent e) {
    if (getSelectedRowCount() > 1) {
      return;
    }
    draggedIndex = rowAtPoint(e.getDragOrigin());
    if (draggedIndex < 0) {
      return;
    }
    try {
      e.startDrag(DragSource.DefaultMoveDrop, (Transferable) this,
                  new TableDragSourceListener());
    } catch (InvalidDnDOperationException idoe) {
      idoe.printStackTrace();
    }
  }

  // Interface: Transferable
  @Override public Object getTransferData(DataFlavor flavor) {
    return this;
  }
  @Override public DataFlavor[] getTransferDataFlavors() {
    DataFlavor[] f = new DataFlavor[1];
    f[0] = this.FLAVOR;
    return f;
  }
  @Override public boolean isDataFlavorSupported(DataFlavor flavor) {
    return flavor.getHumanPresentableName().equals(NAME);
  }

  class CDropTargetListener implements DropTargetListener {
    @Override public void dragExit(DropTargetEvent e) {
      targetIndex = -1;
      repaint();
    }
    @Override public void dragEnter(DropTargetDragEvent e) {
      if (isDragAcceptable(e)) {
        e.acceptDrag(e.getDropAction());
      } else {
        e.rejectDrag();
      }
    }
    @Override public void dragOver(final DropTargetDragEvent e) {
      if (isDragAcceptable(e)) {
        e.acceptDrag(e.getDropAction());
        setCursor(DragSource.DefaultMoveDrop);
      } else {
        e.rejectDrag();
        setCursor(DragSource.DefaultMoveNoDrop);
        return;
      }
      initTargetLine(e.getLocation());
      repaint();
    }
    @Override public void dropActionChanged(DropTargetDragEvent e) {
      // if (isDragAcceptable(e)) { e.acceptDrag(e.getDropAction()); }
      // else e.rejectDrag();
    }
    @Override public void drop(DropTargetDropEvent e) {
      DefaultTableModel model = (DefaultTableModel) getModel();
      if (isDropAcceptable(e)) {
        if (targetIndex == draggedIndex) {
          setRowSelectionInterval(targetIndex, targetIndex);
        } else {
          int tg = targetIndex < draggedIndex ? targetIndex : targetIndex - 1;
          model.moveRow(draggedIndex, draggedIndex, tg);
          setRowSelectionInterval(tg, tg);
        }
        e.dropComplete(true);
      } else {
        e.dropComplete(false);
      }
      e.dropComplete(false);
      setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      targetIndex = -1;
      repaint();
    }
    private boolean isDragAcceptable(DropTargetDragEvent e) {
      DataFlavor[] f = e.getCurrentDataFlavors();
      return isDataFlavorSupported(f[0]);
    }
    private boolean isDropAcceptable(DropTargetDropEvent e) {
      Transferable t = e.getTransferable();
      DataFlavor[] f = t.getTransferDataFlavors();
      return isDataFlavorSupported(f[0]);
    }
  }
}
View in GitHub: Java, Kotlin

解説

ドラッグソースとドラッグターゲットをどちらもJTableにして、行の入れ替えがドラッグ&ドロップで出来るようになっています。

このサンプルのドラッグ&ドロップの手順は、行の入れ替え処理などを除けば、JListの項目をドラッグ&ドロップとほぼ同一です。

参考リンク

コメント