如何填充Jlist

时间:2014-05-02 10:04:23

标签: java swing jlabel

我对Jlist有疑问。我想进行数据库选择并将结果字符串放入Jlist。我的选择正常,我可以在控制台中查看结果,但是如何将其放入我的列表?

...
private JList list;
...
final JList list = new JList();
list.setBounds(71, 111, 246, 79);
panelSelect.add(list);
...
try {
    connectionUtility.openConnection();

    String select = "SELECT ID_UN,NUME_UN,ADRESA_UN FROM UNIVER";

    connectionUtility.stm = connectionUtility.conn.prepareStatement(select);
    PreparedStatement pst = (PreparedStatement) connectionUtility.stm;

    ResultSet rs = pst.executeQuery(select);

    while (rs.next()) {

        String univid = rs.getString("ID_UN");
        String univname = rs.getString("NUME_UN");
        String univadresse = rs.getString("ADRESA_UN");

        String label[] = {univid, univname, univadresse};

        //here I need to do something to put the elements into list                     
        // list.addItem ... ???

        //here I view selected data in console and works 100%
        System.out.println("univid : " + univid);
        System.out.println("univname : " + univname);
        System.out.println("univadresse : " + univadresse);

    }

2 个答案:

答案 0 :(得分:1)

首先,要小心,因为你有两个名为list的JList:

...
private JList list; // This declares a first list
...
final JList list = new JList(); // This declares a second list

然后,你可以做这样的事情;

....
DefaultListModel listModel = new DefaultListModel();
list = new JList(listModel);
....
while (rs.next()) {
    String univname = rs.getString("NUME_UN");
    listModel.addElement(univname);
}

答案 1 :(得分:0)

JList组件具有setListData(Object[] ListData)方法,用于设置jlist的数据。 现在,您可以在程序中使用此代码:

String [] ListData={univid , univname , univadresse};
YOUR_JLIST_NAME.setListData(ListData);

希望这有帮助。