Search code examples
javagridbaglayout

Why is this GridBagConstraints code not working?


Hello so I wanted to add text area, text field and a button to my panel. I wanted area to use 3/4 of height and full width, field to use 1/4 of height and 3/4 of width and a button to use 1/4 height and 1/4 width. I post a pic to show what I want to get. Code for this looks like:

// My JPanel class
public MainPanel() {
   setLayout(new GridBagLayout());
   add(area, new GBC(0, 0, 4, 3).setWeight(4,4).setFill(GBC.BOTH));
   add(field, new GBC(0, 3, 3, 1).setWeight(1,1).setFill(GBC.HORIZONTAL));
}

GBC is my class which inherits from GridBagConstraints class:

public class GBC extends GridBagConstraints {

   public GBC(int gridx, int gridy) {
      this.gridx = gridx;
      this.gridy = gridy;
      weightx = 100;
      weighty = 100;
   }

   public GBC(int gridx, int gridy, int gridwidth, int gridheight) {
      this(gridx, gridy);
      this.gridwidth = gridwidth;
      this.gridheight = gridheight;
   }

   public GBC setFill(int fill) {
      this.fill = fill;
      return this;
   }
}

enter image description here

So the problem is that both area and field take half of height and a button is in the center, hidden under field... Look terrible anyway, how to solve if?


Solution

  • That's how it should look like:

    add(area, new GBC(0, 0, 4, 3).setWeight(4,4).setFill(GBC.BOTH));
    add(field, new GBC(0, 3, 3, 1).setWeight(1,1).setFill(GBC.HORIZONTAL));
    

    Also read about weightx and weighty, cause you're using them in wrong way