I’m making a graph-related program so I need to dynamically create/remove columns from a JTable to simulate the adjacency table. I already can create columns when desired but I cannot remove them, because if I remove a column and then I create another column the previous data (from the deleted column) is shown in the newest column.
I have read this is because the column data is not removed from the tablemodel. I have seen examples to hide or show columns but I need really to remove them so then when I get the 2-dimensional matrix of data I don’t have crossed references nor bad data.
First correction:
private DefaultTableModel removeCol(int id){
DefaultTableModel tmp = new DefaultTableModel();
int columnas = modelo.getColumnCount();
for(int i=0;i<columnas;i++){
if(i!=id)
tmp.addColumn(modelo.getColumnName(i));
}
int rows = modelo.getRowCount();
String datos[] = new String[columnas-1];
for(int row=0;row<rows;row++){
for(int col=0,sel=0;col<columnas;col++,sel++){
if(col!=id)
datos[sel] = (String) modelo.getValueAt(row, col);
else
sel--;
}
tmp.addRow(datos);
}
return tmp;
}
When invoking:
DefaultTableModel mo = removeCol(i);
tblTrans = new JTable(mo);
An adjacency matrix may be more easily manipulated in an
AbstractTableModel, where you can explicitly manipulate the rows to elide one column. In outline,