简体   繁体   English

如何手动将jlabels添加到滚动窗格?

[英]how to manually add a jlabels to a scrollpane?

I try to add book names to a scrollpane in netbeans but no label is added when i run the code please help me out.I added the labels manually to a panel which i created and inserted into a scroll pane 我尝试将书名添加到netbeans的滚动窗格中,但在运行代码时未添加标签,请帮助我。我将标签手动添加到我创建的面板中并插入到滚动窗格中

public void displayBooks(){
        try{
                        java.sql.Connection con = Connectivity.mysql();
            int totalRows,i=1;
            ResultSet rs;
            Statement st = con.createStatement();
            String qy = "select title from Book order by title;";
            rs = st.executeQuery(qy);
            //Reader rm = rs.getCharacterStream();
            rs.last();
                        totalRows = rs.getRow();
                        rs.beforeFirst();
            Object[] obj = new Object[totalRows+1];
            labels = new JLabel[totalRows+1];
            obj[0] = "";


            ImageIcon icon = new ImageIcon("/root/Pictures/picjpeg");


            while(rs.next()){ 
                                System.out.print(rs.getString(1));
                obj[i] = rs.getString(1);
                labels[i] = new javax.swing.JLabel(rs.getString(1));
                });

                jPanel3.add(labels[i]);
                i++;
            }
                        //pack();
            jComboBox1 = new JComboBox(obj);
        }
        catch(Exception e){
            out.println(e);
        }
    }

but no label is added when i run the code 但我运行代码时未添加标签

By default Swing components has a size of (0, 0) so there is nothing to paint. 默认情况下,Swing组件的大小为(0,0),因此无需绘制任何内容。

So you need to invoke the layout manager AFTER you are finished adding components to the panel. 因此,在将组件添加到面板中之后,需要调用布局管理器。

So the basic structure of your code would be: 因此,代码的基本结构为:

while (rs.next())
{
    panel.add(...);
}

panel.revalidate();  // invokes the layout manager
panel.repaint();  // makes sure the panel is repainted

Edit: 编辑:

layout is already set to group layout..... 版式已设置为组版式.....

Well, you need to specify all kinds of constraints if you want to use GroupLayout. 好吧,如果要使用GroupLayout,则需要指定各种约束。 Read the section from the Swing tutorial on How to Use GroupLayout for more information and working examples. 阅读Swing教程中有关如何使用GroupLayout的部分, 获取更多信息和工作示例。 I would suggest you don't want to use a GroupLayout. 我建议您不要使用GroupLayout。

Looks to me like you are just display a column of Icons. 在我看来,您只是显示一列图标。 I would look at using JList for this. 我将为此使用JList。 The tutorial also has a section on How to Use LIsts . 本教程还包含有关How to Use LIsts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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