更新数据库后刷新JTable数据

时间:2013-06-15 21:55:15

标签: java swing vector jtable

我有一个使用Netbeans GUI创建者创建的JTable,并使用Vector对象填充表。我希望在对数据库进行更改后更新表。我不知道该怎么做。有人可以指导我这样做吗?

1 个答案:

答案 0 :(得分:0)

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);
    }