繁体   English   中英

如何使用while循环创建多个JLabel

[英]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.

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