【发布时间】:2014-09-17 10:13:36
【问题描述】:
我需要从数据库中获取所有值并将其放入 JTable 中,填充所有行。 我的代码仅将最后一行放入 JTable 中,而错过了所有先前的行。 有人知道如何从数据库中获取所有值并将它们全部插入 JTable 中吗?
try{
Class.forName("com.mysql.jdbc.Driver");
conn3 = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=123456");
stmt3 = conn3.createStatement();
rs3 = stmt3.executeQuery("SELECT * FROM teams");
String str1 = null,str2 = null,str3 = null,str4 = null,str5 = null;
while (rs3.next())
{
str1 = rs3.getString(1);
str2 = rs3.getString(2);
str3 = rs3.getString(3);
str4 = rs3.getString(4);
str5 = rs3.getString(5);
}
Object[][] data = {{str1,str2,str3,str4,str5}};
String[] columnNames = {"id","Name","Players","Point","Position" };
table = new JTable(data,columnNames);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(10, 321, 297, 143);
frame.getContentPane().add(table);
rs3.close();
stmt3.close();
conn3.close();
}
catch (SQLException se)
{
System.out.println( "SQL Exception:" );
while( se != null )
{
System.out.println( "State : " + se.getSQLState() );
System.out.println( "Message: " + se.getMessage() );
System.out.println( "Error : " + se.getErrorCode() );
se = se.getNextException();
}
}
catch (ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
}
【问题讨论】:
-
1)
table.setBounds(..);Swing GUI 可能必须在不同的平台上工作,使用不同的 PLAF,在不同的屏幕尺寸和分辨率上使用不同的默认字体大小设置。因此,它们不利于组件的精确放置。而是使用布局管理器,或 combinations of layout managers 以及 layout padding and borders 用于空白。 2)frame.getContentPane().add(table);在应用程序中添加表格。启动。数据库查询完成后,设置新的表模型。
标签: java mysql swing jdbc jtable