MichaelMitchell
MichaelMitchell

Reputation: 1167

JPanel GridBagLayout not aligning vertical objects

The problem with the following code is that it is splitting the MenuPane in half instead of the desired 10% to 90%

TitlePane and ControlPane are just JPanels.

public class MenuPane extends JPanel {

public MenuPane( int width, int height ){

    setSize( width, height );

    setLayout( new GridBagLayout() );

    GridBagConstraints c = new GridBagConstraints();

    c.gridx = 0;
    c.gridy = 0;

    c.weightx = 0.0d;
    c.weighty = 0.1d;

    add( new TitlePane( this.getWidth(), (int) (this.getHeight()*c.weighty) ), c );


    c.gridx = 0;
    c.gridy = 1;

    c.weightx = 0.0d;
    c.weighty = 0.9d;

    add( new ControlPane( this.getWidth(), (int) (this.getHeight()*c.weighty) ), c );

}

}

Upvotes: 0

Views: 76

Answers (1)

camickr
camickr

Reputation: 324098

add( new TitlePane( this.getWidth(), (int) (this.getHeight()*c.weighty) ), c );

Don't really know what that code does, but components don't have a size until the component is displayed on a visible GUI. So your getWidth()/Height() methods will return 0.

If you want components to be displayed in a 90/10 ratio then the initial preferred size must also be in a 90/10 ratio. The weighty factor only applies when a component is resized.

I don't know what your ControlPane code looks like so I can't suggest a specific change to make.

You could try using the Relative Layout which was designed specifically for this. You just need to specify the ration when you add the components to the container and it will manage the size from there.

Upvotes: 2

Related Questions