34

如何设置 JTable 以便能够将行拖动到表中的不同索引。例如,如果我有 5 行并且我想将第 4 行拖到第 2 位?

4

5 回答 5

58

以下允许 JTable 对单个拖动行重新排序:

  table.setDragEnabled(true);
  table.setDropMode(DropMode.INSERT_ROWS);
  table.setTransferHandler(new TableRowTransferHandler(table)); 

您的 TableModel 应实现以下内容以允许重新排序:

public interface Reorderable {
   public void reorder(int fromIndex, int toIndex);
}

这个 TransferHandler 类处理拖放,并在手势完成时调用 TableModel 上的 reorder()。

/**
 * Handles drag & drop row reordering
 */
public class TableRowTransferHandler extends TransferHandler {
   private final DataFlavor localObjectFlavor = new ActivationDataFlavor(Integer.class, "application/x-java-Integer;class=java.lang.Integer", "Integer Row Index");
   private JTable           table             = null;

   public TableRowTransferHandler(JTable table) {
      this.table = table;
   }

   @Override
   protected Transferable createTransferable(JComponent c) {
      assert (c == table);
      return new DataHandler(new Integer(table.getSelectedRow()), localObjectFlavor.getMimeType());
   }

   @Override
   public boolean canImport(TransferHandler.TransferSupport info) {
      boolean b = info.getComponent() == table && info.isDrop() && info.isDataFlavorSupported(localObjectFlavor);
      table.setCursor(b ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
      return b;
   }

   @Override
   public int getSourceActions(JComponent c) {
      return TransferHandler.COPY_OR_MOVE;
   }

   @Override
   public boolean importData(TransferHandler.TransferSupport info) {
      JTable target = (JTable) info.getComponent();
      JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
      int index = dl.getRow();
      int max = table.getModel().getRowCount();
      if (index < 0 || index > max)
         index = max;
      target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      try {
         Integer rowFrom = (Integer) info.getTransferable().getTransferData(localObjectFlavor);
         if (rowFrom != -1 && rowFrom != index) {
            ((Reorderable)table.getModel()).reorder(rowFrom, index);
            if (index > rowFrom)
               index--;
            target.getSelectionModel().addSelectionInterval(index, index);
            return true;
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return false;
   }

   @Override
   protected void exportDone(JComponent c, Transferable t, int act) {
      if ((act == TransferHandler.MOVE) || (act == TransferHandler.NONE)) {
         table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      }
   }

}
于 2011-01-22T18:05:31.983 回答
3

查看 Java 教程的拖放部分。有一些关于如何为JTable.

于 2009-03-13T23:51:44.873 回答
1

我喜欢 Soley 的修改,但他的代码依赖于外部库,我不确定他是从哪里得到的,所以我重新编写了它,这样你就不需要 TableUtil 类了……

 @Override
   public boolean importData(TransferHandler.TransferSupport info) {
     JTable target = (JTable) info.getComponent();
        JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
        int index = dl.getRow();
        int max = table.getModel().getRowCount();
        if (index < 0 || index > max) {
            index = max;
        }
        target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

        try {
            Integer rowFrom = (Integer) info.getTransferable().getTransferData(localObjectFlavor);
            if (rowFrom != -1 && rowFrom != index) {

                int[] rows = table.getSelectedRows();
                int iter = 0;
                for (int row : rows) {
                    if (index > row) {
                        index--;
                        ((Reorderable) table.getModel()).reorder(row - iter, index);
                    }

                    else {
                        ((Reorderable) table.getModel()).reorder(row, index);
                    }
                    index++;
                    iter++;
                }

                target.getSelectionModel().addSelectionInterval(index, index);

                return true;
            }

      } catch (Exception e) {
            String error = e.getMessage();
            JOptionPane.showMessageDialog(null, error, "Error", JOptionPane.ERROR_MESSAGE);
      }
      return false;
   }
于 2019-06-22T14:48:41.290 回答
0

也许…… 像这样:

    table.addMouseMotionListener(new MouseMotionListener() {
    public void mouseDragged(MouseEvent e) {
        e.consume();
        JComponent c = (JComponent) e.getSource();
        TransferHandler handler = c.getTransferHandler();
        handler.exportAsDrag(c, e, TransferHandler.MOVE);
    }

    public void mouseMoved(MouseEvent e) {
    }
});
于 2009-03-16T08:46:33.160 回答
0

仅用于记录和多行重新排序:

在某处使用......

 JTable table = t_objects;
    table.setDragEnabled(true);
    table.setDropMode(DropMode.INSERT_ROWS);
    table.setTransferHandler(new TableRowTransferHandler(table));

这是上述答案中的主要类,我对其进行了修改以匹配多行 DnD 的需求。我所做的只是使用第一个选定的行,然后计算放置位置上方的行。删除选定的项目并将它们保存在对象列表中(行数组对象)。然后将它们插入回计算行。最后选择删除/拖动的行以完成该过程。

public class TableRowTransferHandler extends TransferHandler {

    private final DataFlavor localObjectFlavor = new DataFlavor(Integer.class, "Integer Row Index");
    private JTable table = null;

    public TableRowTransferHandler(JTable table) {
        this.table = table;
    }

    @Override
    protected Transferable createTransferable(JComponent c) {
        assert (c == table);
        return new DataHandler(new Integer(table.getSelectedRow()), localObjectFlavor.getMimeType());
    }

    @Override
    public boolean canImport(TransferHandler.TransferSupport info) {
        boolean b = info.getComponent() == table && info.isDrop() && info.isDataFlavorSupported(localObjectFlavor);
        table.setCursor(b ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
        return b;
    }

    @Override
    public int getSourceActions(JComponent c) {
        return TransferHandler.COPY_OR_MOVE;
    }

    @Override
    public boolean importData(TransferHandler.TransferSupport info) {
        JTable target = (JTable) info.getComponent();
        JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
        int index = dl.getRow();
        int max = table.getModel().getRowCount();
        if (index < 0 || index > max) {
            index = max;
        }
        target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

        try {
            Integer rowFrom = (Integer) info.getTransferable().getTransferData(localObjectFlavor);
            if (rowFrom != -1 && rowFrom != index) {

                int[] rows = table.getSelectedRows();
                int dist = 0;
                for (int row : rows) {
                    if (index > row) {
                        dist++;
                    }
                }
                index -= dist;

                //**TableUtil** is a simple class that just copy, remove and select rows.

                ArrayList<Object> list = TableUtil.getSelectedList(table);
                TableUtil.removeSelected(table);
                ArrayList<Integer> sels = new ArrayList<Integer>();
                for (Object obj : list) {
                    sels.add(index);
                    TableUtil.addRowAt(table, obj, index++);
                }
                TableUtil.selectMultipleRow(table, sels);


                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void exportDone(JComponent c, Transferable t, int act) {
        if (act == TransferHandler.MOVE) {
            table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }
}
于 2014-11-05T19:28:03.757 回答