2

I have a question with respect to JScrollPane and a JTable.

I have added a JTable to a JScrollPane, and added the JScrollPane to the JPanel. When I click on 'show' button, the JTable will be filled with contents from the database.

I also have another button reset, clicking on which will remove the contents of the JTable, and the JScrollPane. It is supposed to be doing that, but what happens is that, even after clicking the button, all the contents of the JTable and the JScrollPane still exists.

I used revalidate(), reinstantiate(), etc, but of no use. How do I make it work?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Roshan George
  • 187
  • 2
  • 2
  • 13

2 Answers2

6

Assuming you are using a DefaultTableModel, then you just do:

model.setRowCount(0);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • correct answer, given the less than complete question :-) Wildly guessing that the OP might want to reset the structure as well (the snippet reads in a completely new table) – kleopatra Feb 25 '13 at 13:09
  • I haven't used it but it seems like it will just remove all rows. But the question how to reset it means he wants to remove all data and reload the table. – Arpan May 19 '14 at 17:12
0

In order to remove a row from a JTable, you need to remove the target row from the underlying TableModel. If, for instance, your TableModel is an instance of DefaultTableModel, you can remove a row by doing the following:

((DefaultTableModel)myJTable.getModel()).removeRow(rowToRemove);

Updation 2

To know the rows and delete from jtable

 int rows = myJTable.getRowCount();
 for(int i=0;i<rows;i++)
 ((DefaultTableModel)myJTable.getModel()).removeRow(i);
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • Since I don't know how many rows are there, I think this won't work. – Roshan George Feb 24 '13 at 16:47
  • 2
    Not sure if this deserves a downvote or not. Yes, the removeRow() is used to delete rows. However, when deleting rows you need to start at the last row and decrement i by 1 until you reach zero, otherwise you will only delete half of the rows. – camickr Feb 24 '13 at 21:54
  • -1 for a) @camickr already noted the incorrect looping b) not using api designed to handle the remove _all_ – kleopatra Feb 25 '13 at 13:03