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

查看:721
本文介绍了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;
}

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

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天全站免登陆