Home >Java >javaTutorial >How to Populate a JTable from a ResultSet in Java?

How to Populate a JTable from a ResultSet in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 06:12:13422browse

How to Populate a JTable from a ResultSet in Java?

Populating a JTable from ResultSet

As described in the Java documentation, the JTable constructor accepts a TableModel as an argument. This means that you can use the DefaultTableModel class to create a table model based on a ResultSet.

Here's an example of how to do this:

ResultSet rs = stmt.executeQuery("select * from product_info");
JTable table = new JTable(new DefaultTableModel(buildTableModel(rs), columnNames));

The buildTableModel method takes a ResultSet as an argument and returns a TableModel object. Here's an example of how to implement this method:

public static DefaultTableModel 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 = 1; 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);

}

The above is the detailed content of How to Populate a JTable from a ResultSet in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn