简体   繁体   中英

JTable does not remove row

I need to remove rows form a JTable . I wrote the code like this:

DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
int x = 0;
int row = dtm.getRowCount();

while(row>=x){

    dtm.removeRow(x);
    x++;

}

But it generates an error, like:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 
  24 >= 24

A simpler solution is to use:

dtm.setRowCount(0);

This is also more efficient since the table only needs to repaint itself once, after all the rows have been deleted.

You can try this:

while(row>x){
    dtm.removeRow(x);
    x++;
}

UPDATE

    DefaultTableModel model = new DefaultTableModel(); 
    JTable table = new JTable(model); 

    model.addColumn("Col1"); 
    model.addColumn("Col2"); 
    model.addRow(new Object[]{"1", "2"});
    model.addRow(new Object[]{"1", "2"});

    table.setModel(model);

    for(int index = 0; index<table.getRowCount();)
    {
        model.removeRow(index);
    }

With Java installed it is easier. Sorry about the wrong answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM