views:

652

answers:

4

the problem is in centered layout of components, GridBagLayout always 'sits' in center of JPanel, so I don't care how it will layout components inside, my problem is where these components will start laying out on a panel.

I tried with:

panel.setAlignmentX( JPanel.LEFT_ALIGNMENT );

but it did not helped.

Any idea?

+5  A: 

You need to add at least one component that will fill the horizontal space. If you don't have such a component you can try this:

GridBagConstraints noFill = new GridBagConstraints();
noFill.anchor = GridBagConstraints.WEST;
noFill.fill = GridBagConstraints.NONE;

GridBagConstraints horizontalFill = new GridBagConstraints();
horizontalFill.anchor = GridBagConstraints.WEST;
horizontalFill.fill = GridBagConstraints.HORIZONTAL;    

panel.add(new JLabel("Left Aligned"), noFill);
panel.add(Box.createHorizontalGlue(), horizontalFill);
Nick Holt
A: 

If you want to change where a component is located in a cell created by a GridBagLayout use the parameter anchor from GridBagConstraints.

Bombe
That's not enough, you have to have a component that fills the remaining horizontal space.
Nick Holt
yes I know that; that is not the question, problem is in putting this whole 'grid' in the left upper corner of JPanel which is holding elements, not interfering with GridBags' interior job of laying out components. Just to tell GridBag: ok, guy, you do your job as you like, just sit on left upper corner instead of sitting in centre
ante.sabo
@as: Bombe is right that you need to use the GridBagConstraints.anchor, just missed the bit about the fill component. I believe I'm right in saying GridBagLayout doesn't respect JComponent.setAlignmentX and JComponent.setAlignmentY, both of which apply to the component itself not the contents of a container.
Nick Holt
A: 

I had the same problem as you. Solved it by adding that Panel into another one with BorderLayout and NORTH constraint.

Ondrej

A: 

You can done it by simply use this utility jar painless-gridbag. It also make your code with GridBagLayout much prettier, like following

    PainlessGridBag gbl = new PainlessGridBag(getContentPane(), false);

    gbl.row().cell(lblFirstName).cell(txtFirstName).fillX()
             .cell(lblFamilyName).cell(txtFamilyName).fillX();
    gbl.row().cell(lblAddress).cellXRemainder(txtAddress).fillX();

    gbl.doneAndPushEverythingToTop();
Tri.Bao