Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set size of JLabel in FlowLayout

I have a JPanel that uses FlowLayout. I add a number of JLabels to the JPanel, use setPreferedSize() to adjust their size and save them in a list, label_list. Everything works fine. Then I want to change their size:

for(JLabel c:label_list){
c.setPreferedSize(new Dimension(10,10));
}

And it doesn't work.

c.setBackground(Color.red)

and similar stuff works. Why can't I use setPreferedSize here?

c.setBounds(1,1,10,10) and c.setSize(10,10) Works, but after i update the UI (resizeing the panel) every size goes back to normal.

like image 758
user1506145 Avatar asked Jul 10 '12 09:07

user1506145


People also ask

How do I set the size of a JLabel?

You can set a fixed the size by setting the minimum, preferred and maximum size: setMinimumSize(width, height); setPreferredSize(width, height); setMaximumSize(width, height);

How do I change the size of a label in swing?

You have to use a LayoutManager and then you have to call the pack Method. The LayoutManager tries to arrange the subcomponents and pack() gets the preferred sizes of these subcomponents.

What is the default orientation of FlowLayout?

When the FlowLayout object controls a container with a left-to right component orientation (the default), the LEADING value specifies the components to be left-aligned and the TRAILING value specifies the components to be right-aligned.


1 Answers

Then I want to change their size:

for(JLabel c:label_list){ c.setPreferedSize(new Dimension(10,10)); }

And it doesn't work.

You need to call revalidate() on the parent of the labels so that it reperforms layout and enforces their preferred size.

c.setBounds(1,1,10,10) and c.setSize(10,10) Works, but after i update the UI (resizeing the panel) every size goes back to normal.

Setting bounds/size/location manually conflicts with the LayoutManager of the parent container. The job of the LayoutManager is to position and size the child components.

Either set the layout to null and call yourself setSize-setLocation/setBounds, or use a LayoutManager (recommended) and never call setSize-setLocation/setBounds. At most, you can call setPreferred/setMaximum/setMinimum size but try to avoid this as it can causes cross L&F problems.

like image 84
Guillaume Polet Avatar answered Oct 08 '22 16:10

Guillaume Polet