0

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.

msl2k
  • 13
  • 5

3 Answers3

0

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.

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
0
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);
    }
Master Yoda
  • 4,334
  • 10
  • 43
  • 77
0

"...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.

veganaiZe
  • 539
  • 5
  • 13