'GridLayout with component fixed Width and Height?

I have a 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 preferred size.

I can use other layout if it meets my requirements... but for now only GridLayout allows me to limit columns to 3...

I forgot to mention, Main Panel is added into JScrollpane, so I can scroll vertically.

Solution 1:[1]

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.

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.

  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.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
        } );


This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 markspace