Search code examples
javaswingwhile-loopjpaneljlabel

How do you create multiple JLabels with a while loop


Okay I'm not really familiar with java, so the main deal here is that I'm trying to get contacts(friends if you'd like) from a database and listing them all as JLabels into a JPanel. I'm guessing this is a bad practice but I just want to try giving it a shot.

String query = "SELECT * FROM tblcontacts WHERE user_ID =\""+global.get_username()+"\"";
//Just calling contacts from database with the account logged in
JPanel contactlist = new JPanel();
getContentPane().add(contactlist);
    try{
        Statement stmnt = conn.conn.createStatement();
        ResultSet rs = stmnt.executeQuery(query);
        while(rs.next()){
            //create JLabels here with the contact names and insert it into a JPanel
        }
    }catch(Exception e){
        System.out.println(e);
    }

Im quite stuck with it and I'm not sure how to add the labels in. Really sorry.

*P.s. assume that the panels are working and everything has been set in a nice little window.


Solution

  • Something like this should work

    while(rs.next()){
        //create JLabels here with the contact names and insert it into a JPanel
        JLabel contact = new JLabel(rs.getString(0) + " " + rs.getString(1));
        contactlist.add(contact);
    }
    

    Depending on fields you return with * in the query, index used in rs.getString(<column index>) should be adjusted.