我正在制作一个与图相关的程序,因此我需要从JTable动态创建/删除列以模拟邻接表。我已经可以在需要时创建列,但是无法删除它们,因为如果删除列然后创建另一列,则先前的数据(来自已删除列)将显示在最新列中。

我读过这是因为没有从tablemodel中删除列数据。我已经看到了隐藏或显示列的示例,但是我确实需要删除它们,因此当我获得数据的二维矩阵时,我既没有交叉引用也没有坏数据。

第一次更正:

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;

    }


调用时:

   DefaultTableModel mo = removeCol(i);
    tblTrans = new JTable(mo);

最佳答案

AbstractTableModel中,可以更容易地操纵adjacency matrix,在这里您可以显式操纵行以移出一列。概括来说,

class MatrixModel extends AbstractTableModel {

    private int rows;
    private int cols;
    private Boolean[][] matrix;

    MatrixModel(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        matrix = new Boolean[rows][cols];
    }

    public void deleteColumn(int col) {
        for (Boolean[] row : matrix) {
            Boolean[] newRow = new Boolean[row.length - 1];
            // TODO: copy remaining values
            row = newRow;
        }
        this.fireTableStructureChanged();
    }
    ...
}

10-07 19:10
查看更多