Your Search Bar For Shrewd Tips

How Do I Clear Jtable In Java?


If you want to clear a JTable in Java, clear its table model—not the JTable component itself. A JTable displays data supplied by a TableModel, so the right method depends on the model you use. For the common DefaultTableModel, the simplest solution is usually setRowCount(0). If you use a custom model, clear the data stored in that model and notify the table that it has changed.

This guide explains how to empty a Java Swing JTable, remove rows safely, keep column headers, handle custom models, and avoid common mistakes.

The Quickest Way to Clear a JTable

If your table uses DefaultTableModel, set its row count to zero. This removes all data rows while leaving the column definitions and headers in place:

DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);

For example, a button listener can clear the table like this:

clearButton.addActionListener(event -> {
    DefaultTableModel model =
        (DefaultTableModel) table.getModel();

    model.setRowCount(0);
});

When the model changes, it fires a table-model event. The JTable receives that event and refreshes its display, so you generally do not need to call repaint() yourself.

Why You Clear the Table Model, Not the JTable

A JTable is a Swing component for displaying and editing tabular data. It does not usually own the rows directly. Instead, it asks a TableModel for information such as the number of rows, column names, and cell values. The model is the source of truth; the table is the view.

That distinction matters when clearing data. Removing something from the visual component alone will not empty the underlying model. If the model still contains rows, those rows can reappear when the table refreshes. Update the model, and the table will display the new state.

In many simple applications, the model is a DefaultTableModel. In other applications, it may be a custom class that extends AbstractTableModel, or a model populated from a database or another data source. Identify the model before choosing a clearing method.

Clear Rows with DefaultTableModel

DefaultTableModel provides convenient methods for changing the number of rows. The most direct way to remove every row is setRowCount(0), also known as setNumRows(0). Both leave the model’s columns intact.

DefaultTableModel model =
    (DefaultTableModel) table.getModel();

model.setRowCount(0);

This works whether the table has a few rows or many. It is generally preferable to remove each row one at a time because the model can update its row structure in one operation.

You can also create the model explicitly when building the table. This makes the model type clear and gives you a reference you can reuse:

String[] columnNames = {"Name", "Email", "Status"};

DefaultTableModel model =
    new DefaultTableModel(columnNames, 0);

JTable table = new JTable(model);

// Add data rows as needed.
model.addRow(new Object[] {
    "Avery Chen", "avery@example.com", "Active"
});

// Clear all rows but keep the column headers.
model.setRowCount(0);

The second argument in new DefaultTableModel(columnNames, 0) sets the starting row count to zero. The column names remain available, and you can add new rows later with addRow().

Remove Rows One at a Time

Sometimes you need to remove rows individually—for example, when applying a condition or performing other row-specific work. With DefaultTableModel, call removeRow() using a model row index.

DefaultTableModel model =
    (DefaultTableModel) table.getModel();

while (model.getRowCount() > 0) {
    model.removeRow(0);
}

This loop repeatedly removes the first row until none remain. If you use a standard indexed loop instead, remove rows from the bottom upward. Removing a row shifts the indexes of the rows below it, so moving forward can cause you to skip rows or access an invalid index.

for (int row = model.getRowCount() - 1; row >= 0; row--) {
    model.removeRow(row);
}

For clearing every row in a DefaultTableModel, however, setRowCount(0) is usually shorter and easier to read.

Keep Column Headers or Remove Them Too?

Clearing rows and clearing columns are different operations. Most of the time, you want an empty table that still shows its column headers. Use setRowCount(0) for that result.

If you also want to remove all columns, you can remove them from the model:

DefaultTableModel model =
    (DefaultTableModel) table.getModel();

model.setRowCount(0);

while (model.getColumnCount() > 0) {
    model.setColumnCount(model.getColumnCount() - 1);
}

Removing columns changes the table’s structure, so you may need to add the columns back before displaying new data. Avoid removing columns if your goal is only to empty the current results.

Clearing a JTable with a Custom TableModel

A custom table model may store its rows in a list, array, or another collection. In that case, casting it to DefaultTableModel will fail because it is a different model type. Instead, add a clear method to your custom model, update its data, and notify listeners.

For example, a model backed by a list might look like this:

public class PeopleTableModel extends AbstractTableModel {
    private final List<Person> people = new ArrayList<>();

    public void clear() {
        people.clear();
        fireTableDataChanged();
    }

    @Override
    public int getRowCount() {
        return people.size();
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public Object getValueAt(int row, int column) {
        Person person = people.get(row);

        return switch (column) {
            case 0 -> person.getName();
            case 1 -> person.getEmail();
            case 2 -> person.getStatus();
            default -> throw new IndexOutOfBoundsException();
        };
    }
}

Then clear the table by calling the model’s method:

PeopleTableModel model =
    (PeopleTableModel) table.getModel();

model.clear();

The call to fireTableDataChanged() is important. It tells the JTable and any other listeners that the model’s data has changed. Without an appropriate notification, the model could be empty while the table continues to show stale information.

For changes that affect only a known range of rows or cells, a custom model can use more specific notification methods, such as fireTableRowsDeleted() or fireTableCellUpdated(). For a simple full clear, fireTableDataChanged() is a straightforward choice.

Clearing a JTable on the Swing Event Dispatch Thread

Swing components and their models should generally be accessed on the Event Dispatch Thread (EDT). If a button click triggers the clear operation, its action listener already runs on the EDT:

clearButton.addActionListener(event -> {
    model.setRowCount(0);
});

If you need to clear the table from another thread, schedule the update on the EDT with SwingUtilities.invokeLater():

SwingUtilities.invokeLater(() -> {
    model.setRowCount(0);
});

This is especially important when background work is involved, such as loading data from a file or database. Do the slow work in a background task, then update the Swing model on the EDT. Avoid changing the model concurrently from multiple threads.

Clear the Table Before Loading New Data

If a table displays search results, you may want to remove the old rows before adding a fresh result set. Clear the model first, then add the new rows:

model.setRowCount(0);

for (Person person : searchResults) {
    model.addRow(new Object[] {
        person.getName(),
        person.getEmail(),
        person.getStatus()
    });
}

For a large result set, consider building the data in a custom model and replacing or updating it in a controlled way. Repeatedly adding rows can trigger many model events. Whatever approach you use, ensure the final model change is reported so the table updates correctly.

Clearing the visible table does not delete records from a database. It only removes rows from the in-memory model. If the application later reloads the same database query, the records may appear again. To permanently delete database records, use the appropriate database operation, then refresh the model with the desired results.

Common Mistakes When Clearing a JTable

  • Trying to clear the JTable directly: The table displays model data. Change the model instead.
  • Casting every model to DefaultTableModel: This only works when the table actually uses that model. Use the model’s own clear method for custom models.
  • Removing columns by accident: Set the row count to zero if you want to preserve the headers and table structure.
  • Forgetting to notify listeners: A custom model must fire an appropriate table event after its data changes.
  • Removing rows while looping forward: Row indexes shift after each removal. Loop backward or use setRowCount(0).
  • Updating Swing from a background thread: Perform model updates on the Event Dispatch Thread.
  • Assuming the database was changed: Clearing a table model affects the displayed data, not the underlying database.

Choosing the Right Clearing Method

Use the method that matches your model and what you want to preserve:

  • Clear all data rows and keep columns: Call setRowCount(0) on a DefaultTableModel.
  • Remove rows with individual processing: Use removeRow(), preferably from the last row to the first.
  • Use a custom model: Clear the model’s backing collection and fire a table-model event.
  • Remove both rows and columns: Clear the rows, then remove columns only if the table structure should change.
  • Update from another thread: Schedule the model update on the Swing Event Dispatch Thread.

Conclusion

The simplest answer to “How do I clear a JTable in Java?” is to clear its model. If the table uses DefaultTableModel, call setRowCount(0) to remove every row while keeping the column headers. For a custom TableModel, clear the data structure it manages and fire a table event so the view refreshes. Make model changes on the Swing Event Dispatch Thread, and remember that emptying the displayed table does not delete data from a database.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →