[英]How do you create multiple JLabels with a while loop
好的,我對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假定面板正在運行,並且所有內容都已設置在一個漂亮的小窗口中。
這樣的事情應該工作
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>)
使用的rs.getString(<column index>)
。
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);
}
“ ...幾乎所有創建或與Swing組件交互的代碼都必須在事件分發線程上運行。”
while(rs.next()){
EventQueue.invokeLater(() -> {
JLabel contact = new JLabel(rs.getString(columnIndex) + " " + rs.getString(columnIndex2));
contactlist.add(contact);
});
}
根據Predrag Maric的回答,但在EDT上有Swing部分。 這樣可以防止線程干擾和內存一致性錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.