How do I add/remove selected column(s) in a JTable?
-
22-06-2021 - |
Domanda
I am currently able to just add a column to the last column, and remove the last column added.
I am trying to figure out how to add or remove a selected column but its just not working out for me. For example if I have 3 columns 0, 1, and 2, and I want to add a column to 1 or remove column 1.
I spent an hour in the library but the most I was able to get done was removing and adding row to selected place.
Can someone please help?
This is what I have for adding column but it does not do what i want (only adds to the end):
String colName = Integer.toString(i++);
if (colName != null && colName.length() > 0) {
model.addColumn(colName);
table.updateUI();
undo.push(new Object[]{"Column", "Add", colName});
redo.clear();
}
Soluzione
To add a column at an arbitrary index, use the table column model's addColumn()
followed by moveColumn()
:
TableColumn newColumn = // ...
colModel.addColumn(newColumn);
colModel.moveColumn(colModel.getColumnCount() - 1, desiredIndex);
Removing a column at an index should be even easier:
colModel.removeColumn(colModel.getColumn(desiredIndex));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow