Search code examples
javaswinglayout-managergridbaglayout

How to correctly align and position using GridBagConstraints


I'm trying to align my components like the following:

But at the moment they're like this:

The two components are on a JPanel using FlowLayout (constructor contains FlowLayout.LEFT). The first component has these grid bag constraints:

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

And these are the constraints for the second component:

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

I've tried setting the gridy for the second component to GridBagConstraints.RELATIVE but there was no change.

I would also like for this to be possible:


Solution

  • Here is a simple working code for your case with 3 boxes;

            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