Search code examples
javaswingjlabelgridbaglayout

Components overlapping whilst using GridBagLayout


whilst positioning my JLabels I found a problem which till now I could not resolve. The JLabels were overlapping.

This is a snippet from the code regarding the gridbaglayout:

   c = new GridBagConstraints();

   c.gridx = 0;
   c.gridy = 0;
   c.gridwidth = 3;
   c.fill = GridBagConstraints.HORIZONTAL;
   c.ipady = 20;
   c.weightx = 3;
   c.weighty = 1;
   c.insets = new Insets(0,5,5,5);

   all.add(header, c);

   c.gridx = 0;
   c.gridy = 1;
   c.weightx = 2;
   c.weighty = 4;
   c.insets = new Insets(5,5,5,5);

   all.add(sts, c); //this label overlapped

   c.gridx = 1;
   c.gridy = 1;
   c.weightx = 1;
   c.weighty = 5;
   c.insets = new Insets(5,5,5,5);

   all.add(cl, c); //this label overlapped

Thanks in advance


Solution

  • Having a gridwidth of 3 means the component will take up 3 places across the x grid, please read the grid bag layout tutorial http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

    You have the first component at x0 this will extend 3 columns to x2 hence the next avail grid location is x3