Vertical Align of GridBagLayout Panel on BorderLayout.CENTER

30,051

Solution 1

Take a careful look at the Javadoc of each property of the GridBagConstraints class before using it.

import java.awt.*;
import javax.swing.*;

public class Test extends JFrame {

    public static void main(String arg[]) {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JPanel gb = new JPanel(new GridBagLayout());
        JLabel content = new JLabel("Some text");

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.NORTH;
        gbc.weighty = 1;

        gb.add(content, gbc); // gbc is containing the GridBagConstraints
        frame.add(gb, BorderLayout.CENTER);

        frame.setVisible(true);
    }

}

Solution 2

In addition to setting fill to NONE, also set weighty to a non-0 value (e.g. 1.0). This tells the layout to allocate all extra space in the GridBag column to that particular cell, but since the label itself is anchored to the north and set to not fill, the extra space will be allocated beneath the label.

Share:
30,051
Skyfe
Author by

Skyfe

Updated on July 09, 2022

Comments

  • Skyfe
    Skyfe almost 2 years

    What I'm trying to do is place a GridBagLayout Panel on the center of my BorderLayout and vertical align the GridBagLayout panel ( /and text on it ) to the TOP ( because it automaticly puts it in the middle, horizontally AND vertically ).

    So what I basicly tried ( but ended up having the text of the GridBagLayout still in the total middle of the page instead of in the middle x and top y):

    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.imageio.*;
    import javax.swing.BorderFactory;
    import javax.swing.border.*;
    import java.awt.event.*;
    
    public class Test extends JApplet implements MouseListener, ActionListener {
    
     public void init() {
        //create borderlayout
        this.setLayout(new BorderLayout());
        //create a GridBagLayout panel
        JPanel gb = new JPanel(new GridBagLayout());
        JLabel content = new JLabel("Some text");
        //set GridBagConstraints (gridx,gridy,fill,anchor)
        setGBC(0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.NORTH);
        gb.add(content, gbc); //gbc is containing the GridBagConstraints
        this.add(gb, BorderLayout.CENTER);
      }
    
    }
    

    So I tried to use the gridbagconstraints anchor to set the alignment vertically to the north, top, but that seems not to work. I also tried to resize the GridBagLayout panel itself ( to make it have full height of the layout, 100%, using panel.setSize and setPreferredSize ) and then vertically align the elements on it using the gridbagconstraints.anchor, but that didn't work either.

    Can anyone help me out on this?

    Thanks in advance,

    Best Regards, Skyfe.

    So my question is