防止在Java中将重复数据添加到JTable中

时间:2018-04-19 05:51:53

标签: java swing duplicates jtable

如何防止将重复数据添加到Jtable中。

  

这是我的代码。

try {
    URL url = new URL("http://localhost:8080/webservice/rest/bdetails/get");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");

    if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
            + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

        String output;
        String json = "";
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
                        json += output;
        }

        conn.disconnect();
        java.lang.reflect.Type listType = new TypeToken<ArrayList<BDetails>>() {
                }.getType();

        List<BDetails> bList = new Gson().fromJson(json, listType);

        for( BDetails adr : bList) 
        {
            DefaultTableModel model = (DefaultTableModel) pTable.getModel();
            Vector<String> row = new Vector<String>();
            row.add(detail.getUserName());
            row.add(detail.getFirstName());
            row.add(detail.getLastName());
            row.add(detail.getAddress();
            model.addRow( row );
        }
    } catch (IOException | RuntimeException ex) {
            System.out.println(ex);
        } 

当我运行此方法时,它会向表中添加数据。当我再次运行它向表中添加相同的数据。它也是这样做的。我该如何解决这个问题?有谁能够帮我?提前致谢。下面我添加了BDetails类。

  

BDetails Class

public class BDetails 
{
    private String username;
    private String firstName;
    private String lastName;
    private String address;

    public BDetails() {
    }

    public BDetails(String username, String firstName, String lastName, String address) {
        this.username = username;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

2 个答案:

答案 0 :(得分:3)

首先,我使用BDetails并使用Netbeans添加equalshashcode方法。这很重要,因为它提供了评估对象的两个实例是否相同的方法

public class BDetails {

    private String username;
    private String firstName;
    private String lastName;
    private String address;

    public BDetails() {
    }

    public BDetails(String username, String firstName, String lastName, String address) {
        this.username = username;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 13 * hash + Objects.hashCode(this.username);
        hash = 13 * hash + Objects.hashCode(this.firstName);
        hash = 13 * hash + Objects.hashCode(this.lastName);
        hash = 13 * hash + Objects.hashCode(this.address);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final BDetails other = (BDetails) obj;
        if (!Objects.equals(this.username, other.username)) {
            return false;
        }
        if (!Objects.equals(this.firstName, other.firstName)) {
            return false;
        }
        if (!Objects.equals(this.lastName, other.lastName)) {
            return false;
        }
        if (!Objects.equals(this.address, other.address)) {
            return false;
        }
        return true;
    }
}

然后我创建了一个自定义TableModel(我偏见,但我对DefaultTableModel并不感兴趣,这使下一步变得更容易了)

public class BDetailsTableModel extends AbstractTableModel {

    private List<BDetails> rows;
    private String[] columnNames = {"User name", "First name", "Last Name", "Address"};

    public BDetailsTableModel(List<BDetails> rows) {
        this.rows = rows;
    }

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

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

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

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        BDetails details = rows.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return details.getUsername();
            case 1:
                return details.getFirstName();
            case 2:
                return details.getLastName();
            case 3:
                return details.getAddress();
        }
        return null;
    }

}

最后......

List<BDetails> bList = new Gson().fromJson(json, listType);
//for (BDetails adr : bList) {
//    DefaultTableModel model = (DefaultTableModel) pTable.getModel();
//    Vector<String> row = new Vector<String>();
//    row.add(detail.getUserName());
//    row.add(detail.getFirstName());
//    row.add(detail.getLastName());
//    row.add(detail.getAddress();
//    model.addRow(row);
//}
Set<BDetails> unquie = new HashSet<>(bList);
List<BDetails> rows = new ArrayList<>(unquie);
BDetailsTableModel model = new BDetailsTableModel(rows);
pTable.setModel(model);

好的,所有这一切都是将bList添加到Set,这将从列表中删除所有重复项(使用对象的hashcode),将结果添加到一个ArrayList(因为它有一个get方法),然后将其提供给我们的BDetailsTableModel

现在,如果您不想每次都替换TableModel,而是添加结果会变得有点困难,因为您需要管理新数据集的可能性可能包含旧集的副本。

您可以将以下内容添加到BDetailsTableModel ...

public void add(BDetails details) {
    int rowCount = getRowCount();
    if (rows.contains(details)) {
        return;
    }
    rows.add(details);
    fireTableRowsInserted(rowCount, rowCount);
}

public void addAll(List<BDetails> newRows) {
    Set<BDetails> rows = new HashSet<>(newRows);
    addAll(rows);
}

public void addAll(Set<BDetails> newRows) {
    Set<BDetails> allRows = new HashSet<>(rows);
    allRows.addAll(newRows);

    rows = new ArrayList<>(allRows);
    fireTableDataChanged();
}

而不是创建BDetailsTableModel的新实例,只需使用现有实例(来自pTable)并使用上述功能添加新行

答案 1 :(得分:2)

你可以试试这个,

        java.lang.reflect.Type listType = new TypeToken<ArrayList<BDetails>>() {
                }.getType();

        List<BDetails> bList = new Gson().fromJson(json, listType);

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

        for( BDetails adr : bList) 
        {

            Vector<String> row = new Vector<String>();
            row.add(detail.getUserName());
            row.add(detail.getFirstName());
            row.add(detail.getLastName());
            row.add(detail.getAddress();
            model.addRow( row );
        }
在插入数据之前,

model.setRowCount(0)将清除所有行。它对我有用。