【问题标题】:How can I delete the column and its underlying data without hiding it in jtable如何删除列及其基础数据而不将其隐藏在 jtable 中
【发布时间】:2012-08-31 15:00:22
【问题描述】:

我在删除要删除的特定列下的实际数据时遇到困难。 我实际上想删除该列及其基础数据。我可以插入新列,但是当我删除时 再次插入,我之前删除的旧列再次弹出。

感谢任何排序帮助。

提前感谢您。

【问题讨论】:

标签: java swing jtable


【解决方案1】:

数据存储在TableModel

ColumnModel 中删除列只会阻止视图(JTable)显示它。

要删除它,您需要告诉TableModel 也删除列数据。

根据您的实现,您可以使用JTable.setValueAt(value, row, column)TableModel.setValueAt(value, row, column),哪个更方便。

这当然假设您已经实现了setValueAt 方法

【讨论】:

  • 没有理由删除列,使用 setValueAt() 代替
  • 谢谢你们的回答,由于我没有实现 setValueAt 方法,我设法使用以下方法删除了基础数据。很抱歉,在我得到确认我设法找到它的答案后没有尽快回复。
  • 我也会尝试你的答案,以缩短我的程序。
【解决方案2】:

public void removeColumnAndData(JTable table, int vColIndex) { MyTableModel 模型 = (MyTableModel)table.getModel();

     TableColumn col =table.getColumnModel().getColumn(vColIndex);
     int columnModelIndex = col.getModelIndex();
     Vector data = model.getDataVector();
     Vector colIds = model.getColumnIdentifiers();

  // Remove the column from the table
     table.removeColumn(col);

  // Remove the column header from the table model
     colIds.removeElementAt(columnModelIndex);

  // Remove the column data
     for (int r=0; r<data.size(); r++) {
        Vector row = (Vector)data.get(r);
        row.removeElementAt(columnModelIndex);
     }
     model.setDataVector(data, colIds);

  // Correct the model indices in the TableColumn objects
  // by decrementing those indices that follow the deleted column
     Enumeration<TableColumn> enum1 = table.getColumnModel().getColumns();
     for (; enum1.hasMoreElements(); ) {
        TableColumn c = (TableColumn)enum1.nextElement();
        if (c.getModelIndex() >= columnModelIndex) {
           c.setModelIndex(c.getModelIndex()-1);
        }
     }
     model.fireTableStructureChanged();
  }

/*MyDefaultTableModel 类**/

   class MyTableModel extends DefaultTableModel
  {
     String columns[];
     int size;

      public MyTableModel(String col[],int size)
     {
        super(col,size);
        columns = col;
        this.size=size;
     }

      public Vector getColumnIdentifiers()
     {
        return columnIdentifiers;
     }
  }

【讨论】:

    猜你喜欢
    • 2012-12-31
    • 2011-09-16
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多