如何使用GridBagConstraints正确对齐和定位

时间:2019-07-15 10:11:41

标签: java swing layout-manager gridbaglayout

我正在尝试将组件对齐,如下所示:

但是目前他们是这样的:

这两个组件都使用FlowLayout在JPanel上(构造函数包含FlowLayout.LEFT)。第一个组件具有以下网格袋约束:

GridBagConstraints windowTitleLabelConstraints = new GridBagConstraints();
windowTitleLabelConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
windowTitleLabelConstraints.gridx = 0;
windowTitleLabelConstraints.gridy = 0;

这些是第二个组件的约束:

GridBagConstraints column1Constraints = new GridBagConstraints();
column1Constraints.anchor = GridBagConstraints.LAST_LINE_START;
column1Constraints.gridx = 0;
column1Constraints.gridy = 1;

我尝试将第二个组件的gridy设置为GridBagConstraints.RELATIVE,但是没有变化。

我也希望做到这一点:

1 个答案:

答案 0 :(得分:0)

这是一个用于3个盒子的简单工作代码;

        JFrame frame = new JFrame( "Test" );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize( 800, 300 );

        JPanel screen = new JPanel( new GridBagLayout() );
        screen.setBackground( Color.WHITE );
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.BOTH;

        JPanel panel1 = new JPanel();
        panel1.setBackground( Color.RED );
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        gbc.gridx = 0;
        gbc.gridy = 0;
        screen.add( panel1, gbc );

        JPanel panel2 = new JPanel();
        gbc.anchor = GridBagConstraints.LAST_LINE_START;
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel2.setBackground( Color.ORANGE );
        screen.add( panel2, gbc );

        JPanel panel3 = new JPanel();
        panel3.setBackground( Color.BLACK );
        gbc.anchor = GridBagConstraints.LAST_LINE_END;
        gbc.gridx = 1;
        gbc.gridy = 1;
        screen.add( panel3, gbc );

        frame.add( screen );
        frame.setVisible( true );

enter image description here