Home >Java >javaTutorial >How to Prevent Duplicate Rows in a JTable When Using a Custom Data Model?

How to Prevent Duplicate Rows in a JTable When Using a Custom Data Model?

DDD
DDDOriginal
2024-12-25 22:33:12617browse

How to Prevent Duplicate Rows in a JTable When Using a Custom Data Model?

Duplicate Values in JTable Rows Resolved

Despite populating the JTable with a custom DataModel, repetitive data persisted in each row. However, upon closer inspection, the data model remained intact.

Investigation and Resolution

The issue stemmed from unintentionally referencing the same row data multiple times. The solution involved ensuring that each row contained a distinct array list.

Sample Code

Here's a complete code sample demonstrating the corrected implementation:

public void populate(Collection c) {
    data.clear();
    for (Item i : c.getItems()) {
        ArrayList<String> row = new ArrayList<>(); // Create a new array list for each row
        for (Property p : i.getProperties().values()) {
            row.add(p.toString());
        }
        data.add(row);
    }
    fireTableDataChanged();
}

By creating a separate array list for each row, the data model and JTable accurately displayed the intended data.

The above is the detailed content of How to Prevent Duplicate Rows in a JTable When Using a Custom Data Model?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn