How to insert a column at a specific position in JTable

11,906

Solution 1

Is it really necessary to add the column in your TableModel at a specific index ? You can more easily adjust the column order in the view (the JTable) as documented in the class javadoc of JTable

By default, columns may be rearranged in the JTable so that the view's columns appear in a different order to the columns in the model. This does not affect the implementation of the model at all: when the columns are reordered, the JTable maintains the new order of the columns internally and converts its column indices before querying the model.

This is achieved by using the JTable#moveColumn method.

Adding a column to your DefaultTableModel is done calling the DefaultTableModel#addColumn method

Solution 2

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.

    JTable table = new JTable(rows, cols);
    table.setAutoCreateColumnsFromModel(false);

    DefaultTableModel model = (DefaultTableModel)table.getModel();
    TableColumn col = new TableColumn(model.getColumnCount());

    col.setHeaderValue(headerLabel);
    table.addColumn(col);
    model.addColumn(headerLabel.toString(), values);
    table.moveColumn(table.getColumnCount()-1, vColIndex);
Share:
11,906
MhdSyrwan
Author by

MhdSyrwan

Muhammad Seyrawan, Software Engineer Studied Informatics Engineering in Damascus University.

Updated on June 04, 2022

Comments

  • MhdSyrwan
    MhdSyrwan almost 2 years

    I have a JTable with a predefined model

    how to ask the model to insert a specific column in a specific position ?

    so i want something like : DefaultTableModel.insertRow(int,Object[]) for columns