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"});

Comments

12 Jan 2010 - 6:13am by Vivek Kothari (not verified)

I wanted to know how to give input to the commands we execute using Runtime.getRuntime().exec() if i want to run a C program which has a scanf statement it doesn't work. otherwise it works fine

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.