'How to get the whole row of a JTable to save it into another table?

I am trying to validate that when the column step is equal to 2 the row is copied to another JTable.

But the jtable_step2 I have not initialized correctly, that's why it returns the error:

jtable_step2.setValueAt(jtable.getValueAt(i, j), row, j);

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

How do I copy the same columns and rows that satisfy the condition?

Java code:

import javax.swing.JTable;

public class TestJTableCopy {

    public static void main(String args[]){
        String data[][]={ {"1","/LOCAL/USER/LOCAL", "20220421", "1"},
                          {"1","/LOACL/USER/LOCAL", "20220421", "2"},
                          {"1","/LOACL/USER/LOCAL", "20220422", "2"} };
        String columns[] = {"LINE", "SOURCE", "DATE", "STEP"};
        final JTable jtable = new JTable(data,columns);
        
        JTable jtable_step2 = new JTable();
        //jtable2.addColumn(columns);
        int row = 0;
        for (int i = 0; i < jtable.getRowCount(); i++) {
            //STEP == 2
            if (jtable.getValueAt(i, 3).equals("2")) {

                for(int j = 0; j < jtable.getColumnCount(); j++) {
                    jtable_step2.setValueAt(jtable.getValueAt(i, j), row, j);
                }
                row++;
            }
        }
        
        for (int i = 0; i < jtable_step2.getRowCount(); i++) {
            for (int j = 0; j < jtable_step2.getColumnCount(); j++) {
                System.out.println(i + " " + j + " " + jtable_step2.getValueAt(i, j));
            }
        }
   }
}


Solution 1:[1]

jtable_step2.setValueAt(jtable.getValueAt(i, j), row, j);

You can't use the setValueAt(...) method because the row doesn't exist in the second table. You need to add a new row of data to the model of the table.

You do this by:

  1. Creating a Vector, lets say "row"
  2. Iterate through all the columns of the row you want to copy and add each item to the table
  3. in the second table you use jtable_step2.addRow( row ) to add a new row of data to the model of the table.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 camickr