2

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

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

第一次更正:

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

4 回答 4

4

邻接矩阵在 中可能更容易操作AbstractTableModel,您可以在其中显式操作行以省略一列。概括地说,

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();
    }
    ...
}
于 2012-05-02T04:44:59.803 回答
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();
            }
        });
    }
}
于 2012-05-02T13:57:32.870 回答
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);

}
于 2013-03-14T12:02:00.500 回答
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);       
}
于 2015-04-06T01:48:50.383 回答