Xara
Xara

Reputation: 9098

Removing all the rows of DefaultTableModel

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.

Upvotes: 19

Views: 42999

Answers (6)

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

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();

Upvotes: 45

chamzz.dot
chamzz.dot

Reputation: 775

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

Upvotes: 0

Abdelhak Mahmoudi
Abdelhak Mahmoudi

Reputation: 139

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);
}

Upvotes: 3

mKorbel
mKorbel

Reputation: 109815

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);
    }
}

Upvotes: 15

Shashank Degloorkar
Shashank Degloorkar

Reputation: 3221

Have you tried this This works for me..

defaultTableModel.setRowCount(0);

Upvotes: 14

JB Nizet
JB Nizet

Reputation: 691635

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.

Upvotes: 10

Related Questions