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

How to correctly align and position using GridBagConstraints

我正在尝试按如下方式对齐我的组件:

但现在他们是这样的:

这两个组件在使用 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,但没有任何变化。

我也希望这成为可能:

这是一个简单的工作代码,适用于您的 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 );