【问题标题】:How do you create multiple JLabels with a while loop如何使用 while 循环创建多个 JLabel
【发布时间】:2015-02-11 04:51:42
【问题描述】:

好吧,我对 java 不是很熟悉,所以这里的主要交易是我试图从数据库中获取联系人(如果你愿意的话,朋友)并将它们作为 JLabels 全部列出到 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);
    }

我很坚持,我不知道如何添加标签。真的很抱歉。

*附注假设面板正在工作,并且所有内容都已设置在一个漂亮的小窗口中。

【问题讨论】:

    标签: java swing while-loop jpanel jlabel


    【解决方案1】:

    这样的东西应该可以工作

    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>) 中使用的索引。

    【讨论】:

      【解决方案2】:
      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);
          }
      

      【讨论】:

        【解决方案3】:

        “...几乎所有创建 Swing 组件或与 Swing 组件交互的代码都必须在事件调度线程上运行。”

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

        根据 Predrag Maric 的回答,但在 EDT 上有 Swing 部分。这可以防止线程干扰和内存一致性错误。

        【讨论】:

          猜你喜欢
          • 2015-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-07
          • 2018-12-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多