Inserting a Column in a JTable Component

There is no insertColumn method like DefaultTableModel.insertRow() for inserting rows. In order to insert a column at a particular position, you must append the column using DefaultTable.addColumn() and then move the new column into the desired position. See Appending a Column to a JTable Component and Moving a Column in a JTable Component for more information.
int rows = 10; int cols = 5; JTable table = new JTable(rows, cols); // Disable autoCreateColumnsFromModel table.setAutoCreateColumnsFromModel(false); // Add data // Insert a new column at position 2 (becomes 3rd column) insertColumn(table, "New Column", null, 2); // Insert a new column at the end insertColumn(table, "New Column", null, table.getColumnCount()); // Creates a new column at position vColIndex public void insertColumn(JTable table, Object headerLabel, Object[] values, int vColIndex) { // This method is defined in // Appending a Column to a JTable Component betterAddColumn(table, headerLabel, values); table.moveColumn(table.getColumnCount()-1, vColIndex); }

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.