If you want to display a JTable that displays data from a DataBase ResultSet you can do it manually using JTable that displays data converted from database table ResultSet into Object [ ][ ].
Another approach is to build the JTable model dynamically using the ResultSet meta data. In this article you can see an example of how this can be achieved.
The main idea is hidden in this method which dynamically generates a model from given ResultSet
private 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 usage in the application might then be like in the following code
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://example.com:3306/eshop";
String user = "john_doe";
String password = "P@ssw0rd";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("select * from product_info");
Main window = new Main();
window.setPreferredSize(new Dimension(800, 600));
window.setMinimumSize(new Dimension(400, 230));
window.setTitle("Database binding demo");
window.setBounds(100, 100, 697, 524);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// It creates and displays the table
JTable table = new JTable(window.buildTableModel(rs));
window.getContentPane().add(new JScrollPane(table));
window.setVisible(true);
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}