Position Component at the Top of the Grid Cell with GridBagLayout in Java



To position components at the top fo the grid cell, set the GridBagConstraints. Let’s say we have a panel and within that two CheckBox components −

JPanel panel1 = new JPanel(new GridBagLayout());
JCheckBox checkBox1 = new JCheckBox("Undergraduate");
JCheckBox checkBox2 = new JCheckBox("Graduate");

Position the components now −

panel1.add(checkBox1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
   GridBagConstraints.NORTH, GridBagConstraints.NORTH, new Insets(0, 0, 0, 0), 0, 0));
panel1.add(checkBox2, new GridBagConstraints(1, 0, 1, 1, 2.0, 0.0,
   GridBagConstraints.NORTH, GridBagConstraints.NORTH, new Insets(0, 0, 0, 0), 0, 0));

The following is an example to position component at the top of the grid cell with GridBagLayout −

Example

package my;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
      frame.setSize(500, 500);
      JPanel panel1 = new JPanel(new GridBagLayout());
      JCheckBox checkBox1 = new JCheckBox("Undergraduate");
      JCheckBox checkBox2 = new JCheckBox("Graduate");
      panel1.add(checkBox1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
      GridBagConstraints.NORTH, GridBagConstraints.NORTH, new Insets(00, 0, 0), 0, 0));
      panel1.add(checkBox2, new GridBagConstraints(1, 0, 1, 1, 2.0, 0.0,
      GridBagConstraints.NORTH, GridBagConstraints.NORTH, new Insets(00, 0, 0), 0, 0));
      frame.add(panel1);
      frame.setVisible(true);
   }
}

Output


Updated on: 2019-07-30T22:30:26+05:30

618 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements