开发者

how to set size and bound of button which are added on JPanel?

开发者 https://www.devze.com 2022-12-20 18:57 出处:网络
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

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 an开发者_运维问答d position of button (which are added on panel)at all...

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


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]);


Try setMaximumSize ()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号