Search code examples
javaswingmultidimensional-arrayjcomponentgrid-layout

2D grid of JComponents (Swing)


I'm trying to make a 2D grid of JTextFields to represent a level map. I've come to the following for initializing the 2D Array of TextFields:

fields = new TextField[level.rows][level.columns];
TextField field;
    for (int r = 0; r < level.rows; r++) {
        for (int c = 0; c < level.columns; c++) {
            field = new TextField(level.bricks[r][c].type);
            fields[r][c] = field;
        }  

Now I have to add them to the JFrame, but they need to be lined up so that every row gets under the other column. I did find GridLayout, however i'm not very experienced with AWT/Swing, and still don't know how achieve the desired layout. I was expecting there to be some kind of method like gLayout.add(JComponent,row,column).


Solution

  • This should work as you explained, here's a fully working example that puts JLabels in the 5x5 Grid:

    import java.awt.*;
    import javax.swing.*;
    
    public class GridPrb {
      public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        Container cp = frame.getContentPane();
        cp.setLayout(new GridLayout(5, 5));
    
        for(int y = 0; y < 5; y++) {
          for(int x = 0; x < 5; x++) {
            Label l = new Label("x=" + x + ",y=" + y);
            cp.add(l);
          }
        }
        frame.pack();
        frame.setVisible(true);
      }
    }
    

    The end result would look something like this:

    enter image description here

    Hope this helps.