Search code examples
javaswinglayout-managergrid-layoutflowlayout

GridLayout null margins


I put several JPanels, each containing a JLabel + JTextField in a GridLayout (as shown below). I am trying to reduce the spaces between the cells as much as possible. I did the following :

GridLayout resultsPanelLt = new GridLayout( 0, 3, 0, 0 );
resultsPanelLt.setVgap( 0 );
resultsPanelLt.setHgap( 0 );
JPanel resultPanel =  new JPanel( resultsPanelLt );

// I added several panels like this one
JPanel markUpPanel = new JPanel( new FlowLayout( FlowLayout.RIGHT ));
markUpPanel.setPreferredSize( new Dimension(100, 20) );
markUpPanel.setMaximumSize( new Dimension(100, 20) );
markUpPanel.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
markUpPanel.add( new JLabel( "MarkUp" ) );
JTextField markUp = new JTextField();
markUp.setMargin(new Insets(0, 0, 0, 0));
markUpPanel.add( markUp );

resultPanel.add( markUpPanel );

I would like to remove the spaces between rows I would like to remove the spaces between rows or put them to 1px for instance.


Solution

  • When you create and add panels to your resultPanel which has GridLayout, the child panels are created with FlowLayout. Those child panels have 5 pixel horizontal and vertical gaps.

    Create those like this:

    JPanel markUpPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
    

    The FlowLayout class has a constructor where you can specify the horizontal and veritcal gaps, pass 0 pixel to those. If you don't specify them, the default is 5 pixel.