Why does GridLayout not respect my row and column parameters?

Scott Stanchfield

GridLayout respects the first non-zero row or column parameter passed to its constructor. The other value is computed based on the number of components in the container.

For example:

package sample;

import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Test1 {
  public static void main(String[] args) {
    Frame f = new Frame();
    f.setLayout(new GridLayout(3,4));
    f.add(new Button("1"));
    f.add(new Button("2"));
    f.add(new Button("3"));
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {

will create a single column of three buttons, even though you specified 4 columns.

Because of this behavior, I strongly recommend that you always use a "0" for the value that you don't care about. For example:

f.setLayout(new GridLayout(3,0));
  // if you care that there are always three rows

f.setLayout(new GridLayout(0,4));
  // if you care that there are always four columns
About | Sitemap | Contact