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
Release: 2024-12-06 06:12:13
Original
446 people have browsed it

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));
Copy after login

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

}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template