从JTable中删除列

时间:2012-05-01 23:59:27

标签: java swing jtable

我正在创建一个与图形相关的程序,所以我需要动态创建/删除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);

4 个答案:

答案 0 :(得分:4)

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();
    }
    ...
}

答案 1 :(得分:2)

例如

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

public class MyDialog extends JDialog {

    private static final long serialVersionUID = 1L;
    private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
    private Stack<TableColumn> colDeleted = new Stack<TableColumn>();

    public MyDialog() {
        Object[][] data = {{"Mary", "Campione", "Snowboarding", new Integer(5), false},
            {"Alison", "Huml", "Rowing", new Integer(3), true},
            {"Kathy", "Walrath", "Knitting", new Integer(2), false},
            {"Sharon", "Zakhour", "Speed reading", new Integer(20), true},
            {"Philip", "Milne", "Pool", new Integer(10), false}};
        final JTable table = new javax.swing.JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        add(new JScrollPane(table));
        final JButton button1 = new JButton("Add Col");
        final JButton button = new JButton("Remove Last Col");
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                if (table.getColumnCount() > 0) {
                    TableColumn colToDelete = table.getColumnModel().getColumn(table.getColumnCount() - 1);
                    table.removeColumn(colToDelete);
                    table.validate();
                    colDeleted.push(colToDelete);
                    button1.setEnabled(true);
                } else {
                    button.setEnabled(false);
                }
            }
        });
        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                if (colDeleted.size() > 0) {
                    table.addColumn(colDeleted.pop());
                    table.validate();
                    button.setEnabled(true);
                } else {
                    button1.setEnabled(false);
                }
            }
        });
        JPanel southPanel = new JPanel();
        southPanel.add(button);
        southPanel.add(button1);
        add(southPanel, BorderLayout.SOUTH);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        pack();
        setLocation(150, 150);
        setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                MyDialog myDialog = new MyDialog();
            }
        });
    }
}

答案 2 :(得分:0)

因为DefaultModelTable没有removeColumn,所以可以使用此代码:

private String[] getRemainingIdentifiers(int columnIndex) {

    String[] identifiers = new String[table.getColumnCount() - 1];
    int k = 0;

    for(int i = 0; i < table.getColumnCount(); i++) {
        if(i != columnIndex) {
            identifiers[k++] = table.getColumnName(i);
        }
    }

    return identifiers;
}

private void removeColumn(int columnIndex) {

    String[][] data = new String[table.getRowCount()][table.getColumnCount() - 1];

    for(int i = 0; i < table.getRowCount(); i++) {
        for(int j = 0; j < table.getColumnCount(); j++) {

            if(j != columnIndex) {
                if(table.getValueAt(i, j) == null) {
                    table.setValueAt("", i, j);
                }
                if(j < columnIndex) {
                    data[i][j] = table.getValueAt(i, j).toString();
                } else {
                    data[i][j - 1] = table.getValueAt(i, j).toString();
                }
            }
        }
    }

    modeltable = new DefaultTableModel(data, getRemainingIdentifiers(columnIndex));
    table.setModel(modeltable);

}

答案 3 :(得分:0)

DefaultDataModel没有真正的removeColumn()函数,所以我自己编写了一个函数,实际上可以解决这个问题。

private void removeColumn(int index, JTable myTable){
    int nRow= myTable.getRowCount();
    int nCol= myTable.getColumnCount()-1;
    Object[][] cells= new Object[nRow][nCol];
    String[] names= new String[nCol];

    for(int j=0; j<nCol; j++){
        if(j<index){
            names[j]= myTable.getColumnName(j);
            for(int i=0; i<nRow; i++){
                cells[i][j]= myTable.getValueAt(i, j);
            }
        }else{
            names[j]= myTable.getColumnName(j+1);
            for(int i=0; i<nRow; i++){
                cells[i][j]= myTable.getValueAt(i, j+1);
            }
        }
    }

    DefaultTableModel newModel= new DefaultTableModel(cells, names);
    myTable.setModel(newModel);       
}