これを行う 1 つの方法は、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 );
}
} );
}
}