Java JTable 如何在插入删除或更新数据后刷新表模型。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3179136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:08:22  来源:igfitidea点击:

JTable How to refresh table model after insert delete or update the data.

javaswingrefreshjtabletablemodel

提问by user236501

This is my jTable

这是我的 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);

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。但我在想是否有任何最佳实践或更好的方法来做到这一点?

采纳答案by Peter Lang

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

如果您想通知您JTable有关数据更改的信息,请使用
tableModel.fireTableDataChanged()

From the documentation:

文档

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 应该从头开始重新绘制表格。假定表的结构(按照列的顺序)是相同的。

回答by nkvnkv

I did it like this in my Jtable its autorefreshing after 300 ms;

我在我的 Jtable 中是这样做的,它在 300 毫秒后自动刷新;

DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
                return false;
            }
};
JTable table = new JTable();

Timer t = new Timer(300, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                addColumns();
                remakeData(set);
                table.setModel(model);
            }
        });
        t.start();

private void addColumns() {
        model.setColumnCount(0);
        model.addColumn("NAME");
            model.addColumn("EMAIL");} 

 private void remakeData(CollectionType< Objects > name) {
    model.setRowCount(0);
    for (CollectionType Objects : name){
    String n = Object.getName();
    String e = Object.getEmail();
    model.insertRow(model.getRowCount(),new Object[] { n,e });
    }}

I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange

我怀疑它对像 500 多个这样的大量对象会有好处,只有其他方法是在你的类中实现 TableModelListener,但我不明白如何很好地使用它。看看http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange

回答by tom

Would it not be better to use java.util.Observableand java.util.Observerthat will cause the table to update?

使用会不会更好java.util.Observablejava.util.Observer这会导致表更新?

回答by Daniel De León

The faster way for your case is:

您的情况的更快方法是:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

一个或几个单元格变化时的优化方式:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

回答by Sumit Singh

DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed

回答by Achille

try this

尝试这个

public void setUpTableData() {
    DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();

    /**
    * additional code.
    **/
    tableModel.setRowCount(0);
    /**/
    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);
    /**
    * additional code.
    **/
    tableModel.fireTableDataChanged();
    /**/
}