tags:

views:

178

answers:

3

Hello , I have written a code in java using swing.So that i will have a JscrollPane added to JPanel n then I will add buttons of fixed size to JPanel in verticle fashion

JPanel panel=new JPanel(); 
panel.setBackground(Color.WHITE); 
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS; 
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;  
JScrollPane jsp=new JScrollPane(panel,v,h); 
jsp.setPreferredSize(new Dimension(600,600)); 
jsp.setBounds(150,670,850,200); 
frame.add(jsp); 

then I am adding buttons to it at run time.

 for(i=0;i<n;i++)  
{ 
     button[i]=new JButton(); 
     button[i].setBounds(20,y,120,120); 
     button[i].setSize(120,120); 
     button[i].setToolTipText(file[i].toString());        
     button[i].setIcon(Icon); 
     panel.add(button[i]);    
     y=y+140; //initially y=20 so 1st button on x=20,y=20 2nd button on x=20,160
 } 

I want to add a button one below another...(i.e I am getting a verticle scrollbar)

i.e. button1

 button2 

   ' 

   ' 

the problem is the size and bounds of button that I am setting using setsize/preffered size and setbounds is not affecting size and position of button (which are added on panel)at all...

how to do it? can anybody help me???

+1  A: 

Try setMaximumSize ()

Roman
Thanks.....Its working with size using setMaximum size.... but how to set bound?????
PPB
A: 

The size will be determined by the LayoutManager and only certain LayoutManager's respect a Component's preferred size. For example, using a BorderLayout and adding the JButton to the center (i.e. BorderLayout.CENTER) will cause the button to expand to occupy all available space.

From the BoxLayout API: "BoxLayout attempts to arrange components at their preferred widths (for horizontal layout) or heights (for vertical layout).". So in your case all buttons will be made as wide as the widest button. To avoid this case you could use GridBagLayout; there's a tutorial here.

Adamski
If you can check my question(in code line 3) I have set layout manager as suugested by other and problem of getting buttons in column n setting a size is solved now only the problem is position of buttons...... Please help me in that
PPB
Apologies - I missed that line. I've amended my answer; In particularly see the 2nd paragraph.
Adamski
A: 

If you want to set the position and size of the components (by hand), the container should not use an LayoutManager, that is, set it as null to remove the default manager:

    panel.setLayout(null);
    ...
        button[i].setBounds(20, y, 120, 120);
        // setSize is not needed
        ...
        panel.add(button[i]);
Carlos Heuberger