How to insert / delete a column in JTable java

I have no idea what to do. I am creating an application. I need to work with the table, so I use JTable. But I have a lot of problems with this. This seems to work, but when I try to delete a column, that column disappears (only in the GUI), but all the information still exists. Also columncount does not change.
I searched and tried many different codes, but nothing has changed.

 public void addTblCol(JTable table,String name) {
    DefaultTableModel model = (DefaultTableModel)table.getModel();
     TableColumn col = new TableColumn(model.getColumnCount());

    col.setHeaderValue(name);
    table.addColumn(col);
    model.addColumn(name);
    this.realColCnt++;
      };
public void delTblCol(JTable table,int index) {
            DefaultTableModel model = (DefaultTableModel)table.getModel();
          TableColumn col = table.getColumnModel().getColumn(index);
    table.removeColumn(col);
    table.revalidate();
    this.realColCnt--;
      };
+4
source share
4 answers

DefaultTableModelsupports a method setColumnCount()that effectively allows you to remove columns only from the end of the model.

If you want to remove columns from the middle of the model, you will need:

  • DefaultTableModel removeColumn(int column).
  • Vector.remove(int) .
  • , , fireTableStructureChanged(), , , .
+6

, .

JTable API public void removeColumn(TableColumn aColumn) :

aColumn JTable. : ; TableColumn, .

, , , . , TableModel ColumnModel. .

removeColumn(...), , fireXXX(...).


Edit
:

, . , . . ?

, . , , , .

+3

camickr, remove JTable.

public class CustomTableModel extends DefaultTableModel {
    public void removeColumn(int column) {
        // for each row, remove the column
        Vector rows = dataVector;
        for (Object row : rows) {
            ((Vector) row).remove(column);
        }

        // remove the header
        columnIdentifiers.remove(column);

        // notify
        fireTableStructureChanged();
    }
}

Note that it does not check if the column can be deleted.

0
source
jTable1.removeColumn(jTable1.getColumnModel().getColumn(0));
  • replace jTable1 with the name of your table.
  • change the index number inside "getColumn (0)" according to your table.
0
source

All Articles