Search code examples
javaswinggridbaglayout

Getting a good grid layout in a JPanel


I'm working on a project in which I'm simulating (Conway's) Game Of Life in a simple software. The back-end part is finished but I'm having some troubles displaying the cells nicely. What I'm trying to achieve is having y rows and x columns (x and y may differ per simulation). Every cel can be either alive (some color) or dead (another color) and I'd like them to be squares or at least close to squares. I also need to be able modify a specific cell, for example the cell on row 5, column 3 may need to turn into a different color without affecting the other cells.

Because of these requirements I'm currently working with a GridBagLayout but I'm not getting the desired result. I'm facing two problems:

  1. I'm only getting one row while I can modify how many columns I have
  2. I have no idea how to make squares of each individual cell, they are sometimes stretched horizontally/vertically

My current code in which I'm fooling around until I get the right shape:

    //Set grid dimensions
    int gridSizeX = 5;
    int gridSizeY = 5;     
    JFrame f;
    JPanel p;    

    //Set the frame
    f = new JFrame("Window");
    f.setSize(600,400);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //Set the panel
    p = new JPanel();
    p.setLayout(new GridBagLayout());
    p.setBackground(Color.blue);

    //Set the constraints
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 0.5;   

    //The panel that will hold the grid
    JPanel a;

    //Cycle through all fields of the grid and alternate between red and yellow fields
    for (int i = 0; i < gridSizeX; i++)
    {
        for (int j = 0; j < gridSizeY; j++)
        {
            a = new JPanel();
            if (i%2==0)
                a.setBackground(Color.yellow);
            else
                a.setBackground(Color.red);  
            c.gridx = i;
            c.gridy = j;
            p.add(a, c);
        }
    }

    //Make sure the frame and panel are shown
    f.add(p);
    f.setVisible(true);

Solution

    1. You get more rows but the columns of the different rows are colored equally. You therefore don't see the difference. Use (i+j)%2
    2. Besides c.weightx = 0.5 you should also set c.weighty = 0.5