How to adjust a JComponent on top of others using the GridBagLayout

1

Hello Good!

It turns out that I'm starting to try to use the Gridbaglayout to be able to do my interfaces without the help of GUI tools like the Netbeans and I'm currently lost ..

You see, I have a question and if it is possible to accommodate these components in the same way to manual code:

As far as I can see, it is here:

Afterwards, when adding the last component, this happens:

If possible I thank you for telling me.

Method with which I add the components and place them:

SOLUTION: A personal variable GridBagConstraints is added to each JComponent thanks to: @Javi Molla

public void topPanel(){

    pnlTop.setLayout(new GridBagLayout());
    GridBagConstraints clblNombre = new GridBagConstraints();
    GridBagConstraints cnameField = new GridBagConstraints();
    GridBagConstraints clblID = new GridBagConstraints();
    GridBagConstraints cidField = new GridBagConstraints();
    GridBagConstraints ccolorBox = new GridBagConstraints();
    GridBagConstraints cbtnAgregarIns = new GridBagConstraints();
    GridBagConstraints clblOr = new GridBagConstraints();
    GridBagConstraints cbtnAgregarVen = new GridBagConstraints();
    GridBagConstraints clblAgregarComo = new GridBagConstraints();
    //c.fill = GridBagConstraints.HORIZONTAL;
    clblNombre.insets = i;
    clblNombre.gridx = 0;
    clblNombre.gridy = 1;
    pnlTop.add(lblNombre, clblNombre);
    cnameField.gridx = 1;
    cnameField.gridy = 1;
    nameField.setPreferredSize(new Dimension(100,23));
    pnlTop.add(nameField, cnameField);
    clblID.gridx = 2;
    clblID.gridy = 1;
    pnlTop.add(lblID, clblID);
    cidField.gridx = 3;
    cidField.gridy = 1;
    idField.setPreferredSize(new Dimension(100,23));
    pnlTop.add(idField, cidField);
    ccolorBox.gridx = 4;
    ccolorBox.gridy = 1;
    pnlTop.add(colorBox, ccolorBox);
    cbtnAgregarIns.gridx = 5;
    cbtnAgregarIns.gridy = 1;
    pnlTop.add(btnAgregarIns, cbtnAgregarIns);
    clblOr.gridx = 6;
    clblOr.gridy = 1;
    pnlTop.add(lblOr, clblOr);
    cbtnAgregarVen.gridx = 7;
    cbtnAgregarVen.gridy = 1;
    pnlTop.add(btnAgregarVen, cbtnAgregarVen);
    clblAgregarComo.gridx = 6;
    clblAgregarComo.gridy = 0;
    pnlTop.add(lblAgregarComo, clblAgregarComo);
}
    
asked by Extibax 03.09.2018 в 08:08
source

1 answer

0

You must use a new instance of GridBagConstraints for each component because if not, you can end up modifying the previous values and you can unravel everything:

pnlTop.setLayout(new GridBagLayout());

GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = i;
c.gridx = 0;
c.gridy = 1;
pnlTop.add(lblNombre, c);

c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
nameField.setPreferredSize(new Dimension(100,23));
pnlTop.add(nameField, c);
    
answered by 03.09.2018 / 17:23
source