在JList中显示数据库中的数据

时间:2012-08-26 23:47:27

标签: java swing jdbc jlist

我使用以下代码从数据库中检索数据,但我不知道如何在JList中显示它

Class.forName("oracle.jdbc.driver.OracleDriver");
Statement stmt = null;
ResultSet rs;                                                                          
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1/SPL","root","PWD");
stmt=(Statement) conn.createStatement();
rs=stmt.executeQuery(query);
while (rs.next()) 
{
    String stadium = rs.getString("Stadium");
    String city = rs.getString("City");
}

但我想在JList中显示列数据。你能告诉我怎么做吗?


我正在使用以下代码,但它没有在我的画面上显示任何内容,你能告诉我我错在哪里吗?感谢

 String query="SELECT * FROM Location";
 DefaultListModel model=new DefaultListModel();
 DefaultListModel model1=new DefaultListModel();
 try
 {                                              Class.forName("oracle.jdbc.driver.OracleDriver");
Statement stmt = null;
ResultSet rs;                                                                          
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1/SPL","root","PWD");
stmt=(Statement) conn.createStatement();
rs=stmt.executeQuery(query);
while (rs.next()) 
{
String stadium = rs.getString("Stadium");
String city = rs.getString("City");
model.addElement(stadium);
model1.addElement(city);
}
JList list=new JList(model);
JList list1=new JList(model1);
f8.add(jpa1); //f8=frame name,jpa1=panel name
jpa1.add(list);                                 list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);                        list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(1);
JScrollPane listScroller = new JScrollPane(list);                                          
}
catch(SQLException e)
{
System.out.println("Message   : " + e.getMessage());
}

1 个答案:

答案 0 :(得分:5)

JList可能基于ListModel,因此您需要制作一个包含数据的ListModel,然后使用它来制作JList。我会创建一个课程Stadium或其他内容,包含两个String字段,namecity

public class Stadium {
    private String name;
    private String city;

    public Stadium(String name, String city){...}
    //toString()-method to make it display in a meaningful way in the JList
    public String toString(){ return name + " - " + city; }
}

然后你可以写点像

...
DefaultListModel listModel = new DefaultListModel();
while (rs.next()) {
    String name = rs.getString("Stadium");
    String city = rs.getString("City");
    Stadium stadium = new Stadium(name, city)
    listModel.addElement(stadium);
}
JList list = new JList(listModel);

没有尝试编译和测试此代码,但希望这一点很有帮助!