java 在 FlowLayout 中设置 JLabel 的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11410523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set size of JLabel in FlowLayout
提问by user1506145
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:
我有一个使用 FlowLayout 的 JPanel。我将一些 JLabel 添加到 JPanel,使用 setPreferedSize() 调整它们的大小并将它们保存在一个列表中,label_list。一切正常。然后我想改变它们的大小:
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?
和类似的东西有效。为什么我不能在这里使用 setPreferedSize ?
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.
c.setBounds(1,1,10,10) 和 c.setSize(10,10) 有效,但在我更新 UI(调整面板大小)后,每个尺寸都会恢复正常。
采纳答案by Guillaume Polet
Then I want to change their size:
for(JLabel c:label_list){ c.setPreferedSize(new Dimension(10,10)); }
And it doesn't work.
然后我想改变它们的大小:
for(JLabel c:label_list){ c.setPreferedSize(new Dimension(10,10)); }
它不起作用。
You need to call revalidate()
on the parent of the labels so that it reperforms layout and enforces their preferred size.
您需要调用revalidate()
标签的父级,以便它重新执行布局并强制执行其首选大小。
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.
c.setBounds(1,1,10,10) 和 c.setSize(10,10) 有效,但在我更新 UI(调整面板大小)后,每个尺寸都会恢复正常。
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.
手动设置 bounds/size/location 与父容器的 LayoutManager 冲突。LayoutManager 的工作是定位和调整子组件的大小。
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.
要么将布局设置为null
并调用自己的 setSize-setLocation/setBounds,要么使用 LayoutManager(推荐)并且从不调用 setSize-setLocation/setBounds。您最多可以调用 setPreferred/setMaximum/setMinimum size 但尽量避免这种情况,因为它会导致交叉 L&F 问题。