java 具有固定宽度和高度的组件的 GridLayout?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16369230/
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
GridLayout with component fixed Width and Height?
提问by jovanMeshkov
I have main Panel and I'm adding components dynamically into that one.
我有主面板,我正在将组件动态添加到该面板中。
Main Panel has GridLayout limited to 3 columns and 0 rows (0 rows will allow rows to grow infinitely), but the problem is that I want all components to have fixed size or component's preffered size.
主面板的 GridLayout 限制为 3 列和 0 行(0 行将允许行无限增长),但问题是我希望所有组件都具有固定大小或组件的首选大小。
I can use other layout if it meets my requirements... but for now only GridLayout allows me to limit columns to 3...
如果满足我的要求,我可以使用其他布局...但现在只有 GridLayout 允许我将列限制为 3...
...I forgot to mention, Main Panel is added into JScrollpane, so i can scroll vertically.
...我忘了提,主面板被添加到 JScrollpane,所以我可以垂直滚动。
回答by markspace
One way to to do this is to use JPanels. GridLayout will stretch your components, but if you wrap the component in a JPanel, then the JPanel gets stretched. And since JPanel uses FlowLayout, which does not stretch components, your components remain at their preferred size.
一种方法是使用 JPanels。GridLayout 将拉伸您的组件,但如果您将组件包装在 JPanel 中,则 JPanel 会被拉伸。由于 JPanel 使用 FlowLayout,它不会拉伸组件,因此您的组件将保持其首选大小。
Here's an example using JButton. Notice how I add them to a (new) JPanel each loop, then I add the panel to the grid layout.
这是一个使用 JButton 的示例。请注意我如何将它们添加到(新的)JPanel 每个循环,然后我将面板添加到网格布局。
import javax.swing.*;
public class GridLayout {
public static void main( String[] args ) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setLayout( new java.awt.GridLayout( 0, 3 ) );
for( int i = 0; i < 21; i++ ) {
JPanel panel = new JPanel(); // Make a new panel
JButton button = new JButton( "Button "+i );
panel.add( button ); // add the button to the panel...
frame.add( panel ); // ...then add the panel to the layout
}
frame.pack();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
} );
}
}