简体   繁体   English

更新数据库后刷新JTable数据

[英]Refresh JTable data after updating database

I have a JTable that I created with the Netbeans GUI creator and populated the table by using Vector objects. 我有一个用Netbeans GUI创建者创建的JTable,并使用Vector对象填充了该表。 I want the table to be updated after a change is made to the database. 我希望在对数据库进行更改后对表进行更新。 I'm not sure how to do this. 我不确定该怎么做。 Could anyone please guide me through doing this? 有人可以指导我这样做吗?

Try to put this after your update code

rs=st.executeQuery("select * from Table order by columnName");
table.setModel(buildTableModel(rs));



//Create function

private TableModel buildTableModel(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
    // names of columns

        Vector<String> columnNames = new Vector<String>();

        int columnCount = metaData.getColumnCount();

        for (int column = 0; column < columnCount; column++) {

            columnNames.add(metaData.getColumnName(column));

        }

        // data of the table

        Vector<Vector<Object>> data = new Vector<Vector<Object>>();

        while (rs.next()) {

            Vector<Object> vector = new Vector<Object>();

            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {

                vector.add(rs.getObject(columnIndex));

            }

            data.add(vector);

        }

        return new DefaultTableModel(data, columnNames);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM