javaswinglayout-managergrouplayout

How can I use GroupLayout to indent?


Why doesn't the following code indent label c2?

JPanel ep = new JPanel();
            GroupLayout gl = new GroupLayout( ep );
            ep.setLayout( gl );
            gl.setAutoCreateGaps( true );
            gl.setAutoCreateContainerGaps( true );

            JLabel c1 = new JLabel( "c10000000" );
            JLabel c2 = new JLabel( "c20000000" );
            Border b = BorderFactory.createLineBorder( Color.black );
            c1.setBorder( b );
            c2.setBorder( b );

            gl.setHorizontalGroup( gl.createParallelGroup()
                    .addComponent( c1 )
                    .addComponent( c2 )
                    );
            gl.setVerticalGroup( gl.createSequentialGroup()
                    .addPreferredGap( c1, c2, ComponentPlacement.INDENT )
                    .addComponent( c1 )
                    .addComponent( c2 )
                    );

the result of this code is this

Screenshot

The line .addPreferredGap( c1, c2, ComponentPlacement.INDENT ) should indent the second component but it does not. Can someone please explain why?


Solution

  • No it shouldn't. The vertical group goes VERTICALLY down the screen. So, in this case, it goes:

    Gap -> c1 -> c2
    

    If you want to indent the second element, you need to create a sequential group for the second row in your horizontal group, to say "first a gap, then an element". This would be something like:

    gl.setHorizontalGroup( gl.createParallelGroup()
            .addComponent( c1 )
            .addGroup(gl.createSequentialGroup()
                .addPreferredGap(c1, c2, ComponentPlacement.INDENT)
                .addComponent( c2 )
                )
            );
    gl.setVerticalGroup( gl.createSequentialGroup()
            .addComponent( c1 )
            .addComponent( c2 )
        );
    

    Result:

    enter image description here