Moving a row in jTable
Asked Answered
A

3

9

How can one move a row in jTable so that row1 goes to row2's position and row2 goes to row1's position ?

Agapanthus answered 4/10, 2009 at 21:15 Comment(0)
E
9

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

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

Ephedrine answered 4/10, 2009 at 21:27 Comment(2)
I didn't notice that there was a link. it's been helpful. thanks.Agapanthus
The example link has been removed. You will now need to read the API for the proper syntax.Ephedrine
H
6

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.

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.

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);
}
Hyperostosis answered 11/7, 2013 at 15:42 Comment(2)
Have a JTextAreaEditor in one jTable cell. It moves the row, but without the text in the JTextAreaEditor. Any idea to solve this?Oulman
Solved it with zed's solution: https://mcmap.net/q/1152593/-moving-a-row-in-jtableOulman
E
1
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);
}
Examinant answered 4/10, 2009 at 21:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.