java 在 jTable 中移动一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1517396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:51:58  来源:igfitidea点击:

Moving a row in jTable

javaswingjtabletablemodel

提问by Attilah

How can one move a row in jTableso that row1goes to row2's position and row2goes to row1's position ?

如何移动一行,jTable使row1进入row2的位置,而row2进入row1的位置?

回答by camickr

Use the moveRow(...)method of the DefaultTableModel.

使用 的moveRow(...)方法DefaultTableModel

Or, if you aren't using the DefaultTableModel then implement a simliar method in your custom model.

或者,如果您不使用 DefaultTableModel,则在您的自定义模型中实现一个类似的方法。

回答by LAL

Here is my code that I've just developed using the answer in this question. With those function you can select multiple rows at a time and move them down or up in a JTable. I've attached those function to JButton, but i clean them out to make them more readable.

这是我刚刚使用这个问题中的答案开发的代码。使用这些功能,您可以一次选择多行并在JTable. 我已将这些函数附加到JButton,但我将它们清理掉以使其更具可读性。

The last code line of both method (setRowSelectionInterval()) is used to follow the selection on the row being moved, since moveRow()doesn't move the selection but the content of the row.

两种方法 ( setRowSelectionInterval())的最后一行代码都用于跟随要移动的行上的选择,因为moveRow()不会移动选择而是移动行的内容。

public void moveUpwards()
{
    moveRowBy(-1);
}

public void moveDownwards()
{
    moveRowBy(1);
}

private void moveRowBy(int by)
{
    DefaultTableModel model = (DefaultTableModel) table.getModel();
    int[] rows = table.getSelectedRows();
    int destination = rows[0] + by;
    int rowCount = model.getRowCount();

    if (destination < 0 || destination >= rowCount)
    {
        return;
    }

    model.moveRow(rows[0], rows[rows.length - 1], destination);
    table.setRowSelectionInterval(rows[0] + by, rows[rows.length - 1] + by);
}

回答by Zed

TableModel model = jTable.getModel();
for(int col=0; col<model.getColumnCount(); col++) {
  Object o1 = model.getValueAt(row1, col);
  Object o2 = model.getValueAt(row2, col);
  model.setValueAt(o1, row2, col);
  model.setValueAt(o2, row1, col);
}