19

I want to delete all the rows of DefaultTable. I found two common ways to delete them on internet, but none of them works in my case because those methods does not exist in my DefaultTableModel. I wonder why. My code for using DefaultTableModel is

DefaultTableModel Table = (DefaultTableModel) Table.getModel();

One way to delete is

Table.removeRow(Table.getRowCount() - 1);

but this removerow method does not exist in my DefaultTableModel.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Xara
  • 8,748
  • 16
  • 52
  • 82

6 Answers6

45

You can set the row count to 0. setRowCount(0)

Quote from documentation:

public void setRowCount(int rowCount)

Sets the number of rows in the model. If the new size is greater than the current size, new rows are added to the end of the model If the new size is less than the current size, all rows at index rowCount and greater are discarded.

But as you can't find removeRow either I suspect you haven't typed you model variable as DefaultTableModel perhaps, maybe just TableModel?

In that case cast your TableModel to DefaultTableModel like this:

DefaultTableModel model = (DefaultTableModel) table.getModel();
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
  • I have already been using this same typecasting but still this method doesn't exist – Xara May 02 '12 at 13:03
15

Why complicating simple things, but removes must be iterative,

if (myTableModel.getRowCount() > 0) {
    for (int i = myTableModel.getRowCount() - 1; i > -1; i--) {
        myTableModel.removeRow(i);
    }
}

Code example

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.*;

public class RemoveAddRows extends JFrame {

    private static final long serialVersionUID = 1L;
    private Object[] columnNames = {"Type", "Company", "Shares", "Price"};
    private Object[][] data = {
        {"Buy", "IBM", new Integer(1000), new Double(80.50)},
        {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
        {"Sell", "Apple", new Integer(3000), new Double(7.35)},
        {"Buy", "Nortel", new Integer(4000), new Double(20.00)}
    };
    private JTable table;
    private DefaultTableModel model;

    public RemoveAddRows() {

        model = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                int firstRow = 0;
                int lastRow = table.getRowCount() - 1;
                int width = 0;
                if (row == lastRow) {
                    ((JComponent) c).setBackground(Color.red);
                } else if (row == firstRow) {
                    ((JComponent) c).setBackground(Color.blue);
                } else {
                    ((JComponent) c).setBackground(table.getBackground());
                }
                /*if (!isRowSelected(row)) {
                String type = (String) getModel().getValueAt(row, 0);
                c.setBackground("Buy".equals(type) ? Color.GREEN : Color.YELLOW);
                }
                if (isRowSelected(row) && isColumnSelected(column)) {
                ((JComponent) c).setBorder(new LineBorder(Color.red));
                }*/
                return c;
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        JButton button1 = new JButton("Remove all rows");
        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                if (model.getRowCount() > 0) {
                    for (int i = model.getRowCount() - 1; i > -1; i--) {
                        model.removeRow(i);
                    }
                }
                System.out.println("model.getRowCount() --->" + model.getRowCount());
            }
        });
        JButton button2 = new JButton("Add new rows");
        button2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                Object[] data0 = {"Buy", "IBM", new Integer(1000), new Double(80.50)};
                model.addRow(data0);
                Object[] data1 = {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)};
                model.addRow(data1);
                Object[] data2 = {"Sell", "Apple", new Integer(3000), new Double(7.35)};
                model.addRow(data2);
                Object[] data3 = {"Buy", "Nortel", new Integer(4000), new Double(20.00)};
                model.addRow(data3);
                System.out.println("model.getRowCount() --->" + model.getRowCount());
            }
        });
        JPanel southPanel = new JPanel();
        southPanel.add(button1);
        southPanel.add(button2);
        add(southPanel, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        RemoveAddRows frame = new RemoveAddRows();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
PhoneixS
  • 10,574
  • 6
  • 57
  • 73
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • The reason not the complicate simple things is to avoid mistakes like you did here: the if statement is redundant, it does not remove the row at index 0 and it unnecessarily fires an event for each row. – Walter Laan May 02 '12 at 13:53
  • @Walter Laan thanks for notified stupid mistake, with rest I simple disagreed, same with an answers here, – mKorbel May 02 '12 at 14:27
  • Answers below are simpler, namely using `setRowCount(0);` – Marcos Pereira Sep 26 '17 at 11:16
14

Have you tried this This works for me..

defaultTableModel.setRowCount(0);
Shashank Degloorkar
  • 3,151
  • 4
  • 32
  • 50
10

Why don't you read the javadoc of DefaultTableModel?

public void removeRow(int row)

Removes the row at row from the model. Notification of the row being removed will be sent to all the listeners.

public void setDataVector(Vector dataVector, Vector columnIdentifiers)

Replaces the current dataVector instance variable with the new Vector of rows, dataVector.

public void setRowCount(int rowCount)

Sets the number of rows in the model. If the new size is greater than the current size, new rows are added to the end of the model If the new size is less than the current size, all rows at index rowCount and greater are discarded.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

Simply keep removing the table model's first row until there are no more rows left.

// clean table
DefaultTableModel myTableModel = (DefaultTableModel) this.myjTable.getModel(); 
while (myTableModel.getRowCount() > 0) {
       myTableModel.removeRow(0);
}
0

Ypu can write a method

public void clearTable()
  {
    getTableModel().setRowCount(0);
  }

then call this method from the place that you need to clear the table

chamzz.dot
  • 607
  • 2
  • 12
  • 24