connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
table_1.setModel(buildTableModel(result));
方法:
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);
}
结果:
答案 0 :(得分:3)
您需要将JTable
包裹在JScrollPane
内,并将生成的JScrollPane
添加到您的布局中。
您提供的示例代码未显示您如何将JTable添加到应用程序的JPanel或JFrame。
答案 1 :(得分:0)
找到解决方案:
我在jframe中放置了一个JScrollPane,然后使用以下代码:
connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
JTable t=new JTable();
t.setModel(buildTableModel(result));
s1.setViewportView(t);
s1是JScrollPane。
输出: