MhdSyrwan
MhdSyrwan

Reputation: 1633

How to insert a column at a specific position in JTable

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

Upvotes: 2

Views: 13149

Answers (4)

paparoch
paparoch

Reputation: 450

this link may help http://www.roseindia.net/java/example/java/swing/InsertColumn.shtml

public void positionColumn(JTable table,int col_Index) {
 table.moveColumn(table.getColumnCount()-1, col_Index);
  }

Upvotes: -1

giannis christofakis
giannis christofakis

Reputation: 8321

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

Upvotes: 8

Joop Eggen
Joop Eggen

Reputation: 109547

With DefaultTableModel:

At the end one has to call fireDataChanged. There is only an addColumn with several overloads. This is no hindrance as the order of display is independent. One may move a column to another position, and has to take care of view index != column index. To get the correct view index immediately after adding the column, one has to access the JTable and call moveColumn.

I found it at times easier to create a new TableModel and assign that. Or not use the DefaultTableModel.

Upvotes: 0

Robin
Robin

Reputation: 36601

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

Upvotes: 5

Related Questions