tags:

views:

503

answers:

1

Hello people.

I have problems on inserting rows into a JTable and I don't know what the problem is.

I do exactly like this:

((DefaultTableModel)myJTable.getModel()).insertRow(0,webSiteDownloader.getWebSites().toArray());

The webSiteDownloader is one object that have an ArrayList. I can get that array calling the method getWebSites.

The problem is that when I insert one row, adding the second one, the JTbable only shows the first one, but repeated twice. Was I clear enough?

Thks :D

+2  A: 

I'll take a shot into the dark and guess that you want to accomplish something like this:

DefaultTableModel dtm = (DefaultTableModel)myJTable.getModel();
for (MyRowObject row : webSiteDownloader.getWebSites()) {
  dtm.insertRow(0, row.toArray());
}

Is there a special reason that you're using insertRow instead of addRow?

Also, I'd really like to recommend that you roll your own special purpose TableModel by extending AbstractTableModel. Basic untested example:

public class MyTableModel extends AbstractTableModel
{
  protected List<MyObject> rows;

  public MyTableModel()
  {
    rows = new ArrayList<MyObject>();
  }

  public void add(MyObject obj)
  {
    rows.add(obj);
  }

  @Override
  public int getRowCount()
  {
    return rows.size();
  }

  @Override
  public int getColumnCount()
  {
    // This value will be constant, but generally you'd also
    // want to override getColumnName to return column names
    // from an array, and in that case you can return the length
    // of the array with column names instead
    return 2;
  }

  @Override
  public Object getValueAt(int row, int column)
  {
    MyObject obj = rows.get(row);

    // Change this to match your columns
    switch(column) {
      case 0: return obj.getId();
      case 1: return obj.getName();
    }

    return null;
  }
}
Emil H
Icky code. Non-standard formatting. Protected. Missing final. Initialisation in a constructor when it could be done on the declaration line. Some return, some unhandled in a switch. Returning a random (`null`) value instead of throwing an exception. Missing @Override.
Tom Hawtin - tackline
Thanks for the feedback. I'll keep that in mind. :)
Emil H
Your TableModel can't work if you don't call the inherited fireXxxxEvent() methods from AbstractTableModel! Any call to add() won't refresh the JTable!
jfpoilpret
Also true. I'm sorry for all the silly misstakes, here. It was only meant as a basic example to illustrate the principle and as a basic help to get started, so I wasn't a thorough as I should have been.
Emil H