Search code examples
javaswingjtabledefaulttablemodel

jTable select only data where checkbox is chceck


Hi I have a problem with separate data in jTable.

My jTable:

enter image description here

When I click to Second button, so I have two data in jTable. enter image description here

It's correct but when I click to First button again I get same jTable that as jTable in Second button.

enter image description here

This is my code:

DefaultTableModel model = new DefaultTableModel();
model = (DefaultTableModel) jTable1.getModel();

for(int i = 0; i < jTable1.getRowCount(); i++)
{
   if(jTable1.getValueAt(i, 0) == Boolean.FALSE)
   {
       model.removeRow(i);
   }
}

jTable2.setModel(model);

But it doesn't work. Is there anyone who tells me why ?


Solution

  • But it doesn't work. Is there anyone who tells me why ?

    When you remove, for example, row 0, then all the rows shift down by one, but the value of "I" keeps increasing by one so you will "skip" rows every time you remove a row.

    The solution is to start on the last row and decrement "I":

    for(int i = jTable.getRowCount() - 1; i >=0; I--)
    

    It's not a problem.

    Yes it is. You posted example only works because you selected every other row in the table. Try selecting the first two rows and see what happens. Have said that, this is not the real solution to your problem, because you should NOT be removing data from the first TableModel.

    It's correct but when I click to First button again I get same jTable that as jTable in Second button.

    The problem is that you can't delete the data from the first TableModel. You need to create a new TableModel and then "copy" the data from the first TableModel to the second TableModel.