Within a GUI application, a user is encountering an IllegalStateException when updating a DefaultTableModel from a ResultSet. The goal is to display the contents of the ResultSet within a JTable.
The following code provides a straightforward method to create a DefaultTableModel from a ResultSet:
public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); // Column names Vector<String> columnNames = new Vector<>(); int columnCount = metaData.getColumnCount(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); } // Table data Vector<Vector<Object>> data = new Vector<>(); while (rs.next()) { Vector<Object> vector = new Vector<>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(rs.getObject(columnIndex)); } data.add(vector); } return new DefaultTableModel(data, columnNames); }
Utilizing this method, the table can be constructed as follows:
JTable table = new JTable(buildTableModel(rs));
This solution employs a SwingWorker to perform the data loading in a separate thread, enhancing the UI responsiveness. It also utilizes the try-with-resources statement for improved resource management:
public class GUI extends JFrame { // ... private void loadData() { button.setEnabled(false); try (Connection conn = DriverManager.getConnection(url, usr, pwd); Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from customer"); ResultSetMetaData metaData = rs.getMetaData(); // ... while (rs.next()) { // ... } tableModel.setDataVector(data, columnNames); } catch (Exception e) { // ... } button.setEnabled(true); } }
The above is the detailed content of How to Populate a JTable from a ResultSet and Avoid IllegalStateException?. For more information, please follow other related articles on the PHP Chinese website!