我有主面板,我正在将组件动态添加到该面板中。
主面板的 GridLayout 限制为 3 列和 0 行(0 行将允许行无限增长),但问题是我希望所有组件都具有固定大小或组件的首选大小。
如果符合我的要求,我可以使用其他布局...但现在只有 GridLayout 允许我将列限制为 3...
...我忘了提,主面板被添加到 JScrollpane 中,所以我可以垂直滚动。
我有主面板,我正在将组件动态添加到该面板中。
主面板的 GridLayout 限制为 3 列和 0 行(0 行将允许行无限增长),但问题是我希望所有组件都具有固定大小或组件的首选大小。
如果符合我的要求,我可以使用其他布局...但现在只有 GridLayout 允许我将列限制为 3...
...我忘了提,主面板被添加到 JScrollpane 中,所以我可以垂直滚动。
一种方法是使用 JPanels。GridLayout 将拉伸您的组件,但如果您将组件包装在 JPanel 中,则 JPanel 会被拉伸。由于 JPanel 使用 FlowLayout,它不会拉伸组件,因此您的组件将保持其首选大小。
这是一个使用 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 );
}
} );
}
}