Thread: Java: Sorting and Adding a Row in Table

  1. #1
    unleashed alphaoide's Avatar
    Join Date
    Sep 2003
    Posts
    696

    Java: Sorting and Adding a Row in Table

    I can do sorting and adding row separately with no problem. But when I combine the two features, I got a problem because of that two TableModels.

    Here's how the whole thing initialized.
    Code:
    /*
    Tasks extends vector
    TaskTableModel extends AbstractTableModel
    SortFilterModel extends AbstractTableModel
    */
     
    Tasks tasks = new Tasks( new File( "data.xml" ) ); 
    TaskTableModel tableModel = new TaskTableModel( tasks );
    SortFilterModel sorterModel = new SortFilterModel( tableModel );
    JTable table = new JTable( sorterModel );
    The sorting feature is fine, but the adding row is not. Here's how I add row.
    Code:
    Task task = new Task( id, title, new Date() );
    tasks.insertElementAt( task, 0 );
    table.tableChanged( new TableModelEvent(
        tableModel, 0, 0, TableModelEvent.ALL_COLUMNS,
        TableModelEvent.INSERT ) );

    The following is the exception thrown when adding a row
    Code:
    java.lang.ArrayIndexOutOfBoundsException: 25
    at SortFilterModel.getValueAt(SortFilterModel.java:50)
    So, any suggestion to resolve this?
    source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense

  2. #2
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640
    Sorry to be captain obvous, but the problem is that your indexing an array out of bounds. Can we see line 50 of SortFilterModel.java?

  3. #3
    unleashed alphaoide's Avatar
    Join Date
    Sep 2003
    Posts
    696
    Oh, my god. I was just gonna paste you line 50 and *sigh* "There's nothing in there"
    Code:
    return this.model.getValueAt( this.rows[ r ].index, c );
    Turned out I needed to increment the size of "rows" above when adding a row. It's so obvious but all this time I was just thinking that I just need to fire some event and all the rows count will get synchronized automatically.

    I was that close to ditch this project because of this problem. How can't I thank you enough?

    source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense

  4. #4
    unleashed alphaoide's Avatar
    Join Date
    Sep 2003
    Posts
    696
    Dang, it's so hard to maintain the integrity of index while adding, removing, sorting this rows. Anybody has sample code for this? Not just adding, not just removing, not just sorting; but the one that does all.
    source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense

  5. #5
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640
    I would suggest revising your approach. have a routine that sorts and any time you add/delete a table row re-sort.

Popular pages Recent additions subscribe to a feed