How to clear the content (rows) of the JTable

Solved
ajp55 Posted messages 482 Status Member -  
ajp55 Posted messages 482 Status Member -
Hello,
I'm a beginner in Java and I wrote a program that uses a JTable.
My JTable is contained in a JScrollPane to allow for scrolling.
Upon construction, I fill the data in the JTable by doing
 String[] column = {"Tour","Player"}; String[][] rows = { {"01", "02"}, {"02", "12"}, {"21", "22"}, }; JTable myTable = new JTable(rows,column); JScrollPane jscr = new JScrollPane (myTable); 

It fills up well. After a certain number of executions, I needed to delete only the rows from the JTable, but nothing happened. Here’s the code:
 myTable.removeRowSelectionInterval(0, myTable.getRowCount() - 1); myTable.validate(); jscr.validate(); 

It didn’t work. I tried
myTable.removeAll();
still nothing.

Could someone help me?
Thank you in advance for your responses.
Configuration: Windows 7 / Chrome 23.0.1271.97

--
"The computer is a great invention: there are just as many mistakes as before, but no one is responsible anymore..."

1 answer

  1. KX Posted messages 19031 Status Moderator 3 020
     
    It would be better to use a TableModel to manipulate the data:

    String[] column = {"Round","Player"}; String[][] rows = {{"01","02"},{"02","12"},{"21","22"}}; DefaultTableModel model = new DefaultTableModel(rows,column); JTable myTable = new JTable(model); model.addRow(new String[] {"11","10"}); // add a row at the end model.removeRow(n); // remove row 'n' model.setRowCount(0); // remove all rows

    --
    Trust does not exclude control
    0
    1. ajp55 Posted messages 482 Status Member 23
       
      Always nothing. In fact, when I redefine a new TableModel by doing
      JTable myTable = new JTable(new DefaultTableModel(rows, column);
      in that case it works, because it loses the pointer to the old TableModel. *
      Thank you for your response.
      Indeed, I am using a model and it is a function that returns this model. When trying to do as you said, I declared the model as a property of the class, and when emptying the rows, I did
      model.setRowCount(0)
      , but nothing.
      Thanks.
      0
    2. KX Posted messages 19031 Status Moderator 3 020
       
      You can try a rather ugly alternative:

      while (model.getRowCount()!=0) model.removeRow(0);

      Or equivalently:

      for (int n=model.getRowCount()-1; n>=0; n--) model.removeRow(n);
      0
    3. ajp55 Posted messages 482 Status Member 23
       
      Thanks, the
      model.setRowCount(0)
      works, indeed, I had to do
      maTable.setModel(model)
      afterwards for it to take effect.
      Thank you for your help.
      0