简体   繁体   中英

how to delete all rows in jtable?

i have one problem to delete the all rows in my table ,i have one Jpanel which have jtable, when i select the row it will display the corresponding row value ,and when i click another button on same panel means it,will reload the table,here is the problem, i got the exception

Exception in thread "AWT-EventQueue-0"

    java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
        at java.util.Vector.elementAt(Unknown Source)
        at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
        at javax.swing.JTable.getValueAt(Unknown Source)
        at Testsample$16.valueChanged(Testsample.java:1516) 

i almost use all methods to delete rows in table now i use this method

while (table.getRowCount() > 0) {
                    ((DefaultTableModel) table.getModel()).removeRow(0);
                } 

note :i use two panel for this sample application when all controlls are in same it's everything working fine, if i set the table in second panel means ,it throws above exception ,any idea how solve this problem

Try this code..

DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.getDataVector().removeAllElements();

The exception you are seeing is coming from the Swing Thread (AWT-EventQueue-0). The exception is happening because the JTable is drawing itself (on the Swing Thread) at the same time that you are modifying the DefaultTableModel on some other thread.

Do not do that! All changes to the table model must happen on the Swing Thread.

See Last word in Swing Threads

Use EventQueue.invokeLater(new Runnable() {...}); or something similar.

This is my method:

DefaultTableModel model=(DefaultTableModel)table.getModel();
            int rc= model.getRowCount();
            for(int i = 0;i<rc;i++){
                model.removeRow(0);
            }   

I use this code

dtm_vendor = new DefaultTableModel();
jTable_vendor.setModel(dtm_vendor);

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