Question

I have a problem with Jlist. I want to make an DB select and put result string into a Jlist. My select is working, and i can view result in console, but how can I put it into my list?

...
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);

    }
Was it helpful?

Solution

JList component has setListData(Object[] ListData) method for set data of your jlist. Now you can use this code in your program:

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

Hope this helps.

OTHER TIPS

First, be careful because you have two JLists both called list:

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

Then, you can do something like this;

....
DefaultListModel listModel = new DefaultListModel();
list = new JList(listModel);
....
while (rs.next()) {
    String univname = rs.getString("NUME_UN");
    listModel.addElement(univname);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top