The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.table  [62 examples] > Rows  [8 examples]

e909. Inserting a Row in a JTable Component

To insert a row of data to a JTable component, you need to insert it to its table model. A simple implementation of a table model that supports the insertion of row data is DefaultTableModel.

When inserting a row using DefaultTableModel.insertRow(), the position of the new row must be specified. Positions are locations between rows. For example, if there are 2 rows in a table, there are 3 possible positions - - 0, 1,and 2. Inserting a row at position 0 makes the new row the first row. Inserting a row at position 2 makes the new row the last row.

When inserting a row with fewer values than columns, the left-most fields in the new row are populated with the supplied values (left-to-right) and the fields without values are set to null. When inserting a row with more values than columns, the extra values are ignored.

    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    
    // Create a couple of columns
    model.addColumn("Col1");
    model.addColumn("Col2");
    
    // Create the first row
    model.insertRow(0, new Object[]{"r1"});
    
    // Insert a row so that it becomes the first row
    model.insertRow(0, new Object[]{"r2"});
    
    // Insert a row at position p
    int p = 2;
    model.insertRow(p, new Object[]{"r3"});
    
    // Insert a row before the second row
    int r = 1;
    model.insertRow(r, new Object[]{"r4"});
    // the new row is now the second row
    
    // Insert a row after the second row
    r = 1;
    model.insertRow(r+1, new Object[]{"r5"});
    // the new row is now the third row
    
    // Append a row
    model.insertRow(model.getRowCount(), new Object[]{"r5"});

 Related Examples
e907. Getting the Number of Rows and Columns in a JTable Component
e908. Appending a Row to a JTable Component
e910. Removing a Row from a JTable Component
e911. Moving a Row in a JTable Component
e912. Copying a Row or Column in a JTable Component
e913. Setting the Height of a Row in a JTable Component
e914. Shading Rows and Columns in a JTable Component

See also: Cells    Column Heads    Columns    Editing    Events    Layout    Scrolling    Selection    Sorting    Table Model    Tool Tips   


© 2002 Addison-Wesley.