scala 如何仅设置具有流布局的面板的首选宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7633161/
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
How to set only the preferred width of Panel with flow layout?
提问by Rogach
I have a panel with flow layout, and it can contain a variable number of items - from 1 to 2000. I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width. The problem is, when I set preferred size of panel to something like (800,600), some items are missing, and there is no scroll. If I set up preferred size of scroll pane, then all elements in flow pane are put on one very long line.
我有一个带有流布局的面板,它可以包含可变数量的项目 - 从 1 到 2000。我想把它放在一个滚动窗格中,可在垂直方向滚动,并具有固定宽度。问题是,当我将面板的首选大小设置为 (800,600) 时,某些项目丢失了,并且没有滚动。如果我设置滚动窗格的首选大小,那么流窗格中的所有元素都会放在一个很长的行上。
Setting maximum size on any element seems to do nothing at all - layout managers ignore it.
在任何元素上设置最大尺寸似乎什么都不做 - 布局管理器忽略它。
How can I fix this?
我怎样才能解决这个问题?
采纳答案by Heisenbug
You could use BoxLayout to do this:
你可以使用 BoxLayout 来做到这一点:
JPanel verticalPane = new JPanel();
verticalPane.setLayout(new BoxLayout(verticalPane, BoxLayout.Y_AXIS));
JScrollPane pane = new JScrollPane(verticalPane);
//add what you want to verticalPane
verticalPane.add(new JButton("foo"));
verticalPane.add(new JButton("bar"));
This of course will use the preferred size of each component added. If you want to modify the preferred size for example of a JPanel, extend it and override getPreferredSize:
这当然将使用添加的每个组件的首选大小。如果要修改 JPanel 的首选大小,请扩展它并覆盖 getPreferredSize:
class MyPanel extends JPanel(){
public Dimension getPreferredSize(){
return new Dimension(100,100);
}
}
A note: BoxLayout will take in consideration getPreferredSize, other LayoutManager may not.
注意:BoxLayout 会考虑 getPreferredSize,其他 LayoutManager 可能不会。
Please criticize my answer, I'm not sure it's completely correct and I'm curious to hear objections in order to know if I understood the problem.
请批评我的回答,我不确定它是否完全正确,我很想听到反对意见,以便知道我是否理解问题。
回答by camickr
I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width
我想把它放在一个滚动窗格中,可在垂直方向滚动,并具有固定宽度
You can use the Wrap Layoutfor this.
您可以为此使用Wrap Layout。
Don't set the preferred size of the panel. But you can set the preferred size of the scroll pane so the frame.pack() method will work.
不要设置面板的首选大小。但是您可以设置滚动窗格的首选大小,以便 frame.pack() 方法起作用。

