有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用GroupLayout进行缩进?

为什么下面的代码不缩进标签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 )
                    );

这个代码的结果是

Screenshot

.addPreferredGap( c1, c2, ComponentPlacement.INDENT ) 应该缩进第二个组件,但它不缩进。有人能解释一下原因吗


共 (1) 个答案

  1. # 1 楼答案

    不,不应该。垂直组在屏幕上垂直向下。所以,在这种情况下,它是这样的:

    Gap -> c1 -> c2
    

    如果要缩进第二个元素,需要为水平组中的第二行创建一个顺序组,表示“先是间隙,然后是元素”。这大概是:

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

    结果:

    enter image description here