简体   繁体   中英

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

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.

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. Read the section from the Swing tutorial on How to Use GroupLayout for more information and working examples. I would suggest you don't want to use a GroupLayout.

Looks to me like you are just display a column of Icons. I would look at using JList for this. The tutorial also has a section on How to Use LIsts .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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