Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing GridBagLayout Component Positioning

I am using Swing's GridBagLayout for the fist time and I have so far only added two components to a container, although I intend to add more below vertically. So far, the first component (a JLabel) is positioned correctly at PAGE_START, and I have remembered to set weight attributes for the components' corresponding GridBagConstraints. The second component (a JTextField) however is not positioning as I intended and it being centered in the container rather than moving up underneath the JLabel. I have attempted to use multiple anchor constants including FIRST_LINE_START, PAGE_START, NORTH & NORTHWEST but so far nothing is working.

And so, once again I call for the gifted coders of stackoverflow for help. Below is a snippet of the code and below that is an image of the problem graphically.

    // Instantiate components and configure their corresponding GridBagConstraints attributes
    // refPlusType properties
    refPlusType = new JLabel("<html><h3>"+"Reference"+" - "+"Job Type"+" </h3><hr /></html>");
    refPlusTypeGC = new GridBagConstraints();
    refPlusTypeGC.gridx = 0; // Grid position 
    refPlusTypeGC.gridy = 0;
    refPlusTypeGC.gridwidth = 2; // Number of colums occupied by component
    refPlusTypeGC.insets = new Insets(5, 10, 5, 10); // Specifies margin
    refPlusTypeGC.weightx = 0.1; // Required for anchor to work. 
    refPlusTypeGC.weighty = 0.1; // Required for anchor to work. 
    refPlusTypeGC.anchor = GridBagConstraints.PAGE_START; // Position in container

    // addressLine1 properties
    addressLine1 = new JTextField();
    addressLine1GC = new GridBagConstraints();
    addressLine1GC.gridx = 0; 
    addressLine1GC.gridy = 1;
    addressLine1GC.gridwidth = 2; 
    addressLine1GC.insets = new Insets(0, 10, 0, 10); 
    addressLine1GC.fill = GridBagConstraints.HORIZONTAL; // Specifies component fill Horizontal space
    addressLine1GC.weightx = 0.1; 
    addressLine1GC.weighty = 0.1; 
    addressLine1GC.anchor = GridBagConstraints.FIRST_LINE_START;

    // Add components to this HALLogisticsDetailsPanel
    this.add(refPlusType, refPlusTypeGC);
    this.add(addressLine1, addressLine1GC);

Image below;

enter image description here

Thank you all for any help you can offer.

like image 631
Rudi Kershaw Avatar asked Jul 24 '26 14:07

Rudi Kershaw


1 Answers

Try increasing the weighty for addressLine1 to a much larger value. I did a quick test setting it to 1000:

addressLine1GC.weighty = 1000.0;

and that pushed the addressLine1 field up under the label with the whitespace below.

like image 88
Bryan Hutchinson Avatar answered Jul 26 '26 05:07

Bryan Hutchinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!