JTable 如何在插入删除或更新数据后刷新表模型. [英] JTable How to refresh table model after insert delete or update the data.

查看:35
本文介绍了JTable 如何在插入删除或更新数据后刷新表模型.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 jTable

This is my jTable

private JTable getJTable() {
    String[] colName = { "Name", "Email", "Contact No. 1", "Contact No. 2",
            "Group", "" };
    if (jTable == null) {
        jTable = new JTable() {
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            }
        };
    }
    DefaultTableModel contactTableModel = (DefaultTableModel) jTable
            .getModel();
    contactTableModel.setColumnIdentifiers(colName);
    jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    return jTable;
}

我将调用此方法从数据库中检索数据并将其放入表模型

I will call this method to retrieve the data from database and put it into table model

public void setUpTableData() {
    DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
    ArrayList<Contact> list = new ArrayList<Contact>();
    if (!con.equals(""))
        list = sql.getContactListsByGroup(con);
    else
        list = sql.getContactLists();
    for (int i = 0; i < list.size(); i++) {
        String[] data = new String[7];

            data[0] = list.get(i).getName();
            data[1] = list.get(i).getEmail();
            data[2] = list.get(i).getPhone1();
            data[3] = list.get(i).getPhone2();
            data[4] = list.get(i).getGroup();
            data[5] = list.get(i).getId();

        tableModel.addRow(data);
    }
    jTable.setModel(tableModel);
}

目前我正在使用这种方法在更新表数据后刷新表.我先把桌子清零

Currently I was using this method to refresh the table after updating the table data. I will first clear the table

DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
tableModel.setRowCount(0);

然后再次重构表模型,以便刷新jTable.但我在想是否有任何最佳实践或更好的方法来做到这一点?

and then restructure the table model again so it will refresh the jTable. But I was thinking is there any best practices or better way to do that?

推荐答案

如果你想通知你的 JTable 关于你的数据的变化,使用
tableModel.fireTableDataChanged()

If you want to notify your JTable about changes of your data, use
tableModel.fireTableDataChanged()

来自 文档:

通知所有侦听器表格行中的所有单元格值可能已更改.行数也可能发生了变化,JTable 应该从头开始重新绘制表格.假定表的结构(按照列的顺序)是相同的.

Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.

这篇关于JTable 如何在插入删除或更新数据后刷新表模型.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆