Object[][] rowData = {}; Object[] columnNames = { "Column 1", "Column 2", "Column 3", "Column 4", "Column 5", "Column 6" , "Column 7", "Column 8", "Column 9", "Column 10", "Column 11", "Column 12"}; DefaultTableModel listTableModel; listTableModel = new DefaultTableModel(rowData, columnNames); for (int i = 1; i < 12; i++) { String rowString = "777";//SELECT * FROM caipu listTableModel.addRow(new Object[] { rowString, "666", "888" }); } JTable listTable; listTable = new JTable(listTableModel); listTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); listTable.setCellEditor(null); listTable.setBounds(60, 140, 1400, 600); addStartFrame.add(listTable); 在Java Swing中将上面代码使用循环将行将已定义的添加到JTable的代码改为连接数据库使用循环将行连接MySQL表的数据添加到JTable的代码
时间: 2024-03-24 20:38:33 浏览: 108
可以尝试使用JDBC连接MySQL数据库,然后使用ResultSet获取查询结果,最后使用循环将查询结果添加到JTable中。代码示例:
```
Object[] columnNames = { "Column 1", "Column 2", "Column 3", "Column 4", "Column 5", "Column 6", "Column 7", "Column 8", "Column 9", "Column 10", "Column 11", "Column 12"};
DefaultTableModel listTableModel = new DefaultTableModel(null, columnNames);
JTable listTable = new JTable(listTableModel);
listTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
listTable.setCellEditor(null);
listTable.setBounds(60, 140, 1400, 600);
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
Object[] row = new Object[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
row[i] = rs.getObject(i+1);
}
listTableModel.addRow(row);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
addStartFrame.add(listTable);
```
需要替换代码中的数据库连接信息和查询语句,以及表名和列数等信息。同时,需要注意避免在循环中频繁创建TableModel对象,而是应该在循环外部创建TableModel,并在循环中向其中添加数据。
阅读全文