简体   繁体   中英

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.

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

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.

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()){
            //Instantiates a new instance of JLabel for each record
            JLabel label = new Label( "Pass your contact names here as variables );

            //then adds the instance to the panel
            contactList.add( label );
        }
    }catch(Exception e){
        System.out.println(e);
    }

"...almost all code that creates or interacts with Swing components must run on the event dispatch thread."

while(rs.next()){
    EventQueue.invokeLater(() -> {
        JLabel contact = new JLabel(rs.getString(columnIndex) + " " + rs.getString(columnIndex2));
        contactlist.add(contact);
    });
}

As per Predrag Maric's answer but with the Swing portion on the EDT. Which prevents thread interference and memory consistency errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM