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.
You can set a fixed the size by setting the minimum, preferred and maximum size: setMinimumSize(width, height); setPreferredSize(width, height); setMaximumSize(width, height);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With