从JList中

问题描述:

数据库显示的数据我使用下面的代码从数据库中检索数据,但我不知道如何来显示它在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()); 
} 
+3

[“如何使用列表”](http://docs.oracle.com/javase/tutorial/uiswing/components/list.html)将是一个很好的开始 – Sujay

+2

[Data from database to JList](http://*.com/questions/12133621/data-from-database-to-jlist)请编辑原始问题,而不是开始一个新的问题! –

+0

@AndrewThompson:重复:/ ......没有注意到那部分! – Sujay

一个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); 

没有尝试编译和测试该代码,但希望点是有帮助的!