好吧我对java并不熟悉,所以这里的主要交易是我试图从数据库中获取联系人(朋友,如果你愿意)并将它们全部列为JLabel到JPanel中。我猜这是一个不好的做法,但我只是想尝试一下。
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);
}
我非常坚持它,我不知道如何添加标签。真的很抱歉。
* P.S。假设面板正在工作,所有东西都设置在一个漂亮的小窗口中。
答案 0 :(得分:0)
这样的事情应该有效
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);
}
根据您在查询中使用*
返回的字段,应调整rs.getString(<column index>)
中使用的索引。
答案 1 :(得分: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);
}
答案 2 :(得分:0)
“...几乎所有创建或与Swing组件交互的代码都必须在事件派发线程上运行。”
while(rs.next()){
EventQueue.invokeLater(() -> {
JLabel contact = new JLabel(rs.getString(columnIndex) + " " + rs.getString(columnIndex2));
contactlist.add(contact);
});
}
根据Predrag Maric的回答,但在EDT上有Swing部分。这可以防止线程干扰和内存一致性错误。