Search code examples
javaswingjpanelgrid-layoutgridbaglayout

(Java) Using GridLayout (possibly GridBagLayout) on a 2D array of JPanels


I am trying to make a program that allows the user to change the colour of JPanels through mouse interaction. I have the array of JPanels all up and running (5x5) BUT they expand to fit the entire main Panel, no matter the size. Any ideas on how to give them a standard size so they don't fill up the whole window and fit nicely in the middle?

I've been told I may have to use GridBagLayout instead of GridLayout for this, but I have literally no experience with that method, and only just heard the name for the first time, so any help on that would also be class.

public void gridInit() {
        cell = new JPanel [x][x];
        setLayout(new GridLayout(5,5));
        for (int i = 0; i < x; i ++) {
            for (int j = 0; j < x; j ++) {
                cell [i][j] = new JPanel();
                cell [i][j].setBackground(new Color(i*40, j*30, 10));
                cell [i][j].setBorder(loweredetched);
                add(cell [i][j]);           
        }

Edit: I just realised this is my first post NOT about fixing an error, which may be a step forward :)


Solution

  • Put your cells in a GridLayout-using JPanel created to hold them, and then add that JPanel to the main JPanel, using whatever layouts are appropriate for your GUI. Please understand that you can nest JPanels as needed, each using its own layout manager, and thereby allow use of simple layout managers to create complex layouts.

    e.g.,

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class ColorGrid extends JPanel {
       private static final int PREF_W = 750;
       private static final int PREF_H = 550;
       private static final int GRID_ROWS = 5;
       private static final int GRID_COLS = 5;
    
       public ColorGrid() {
          JPanel gridPanel = new JPanel(new GridLayout(GRID_ROWS, GRID_COLS));
          for (int row = 0; row < GRID_ROWS; row++) {
             for (int col = 0; col < GRID_COLS; col++) {
                gridPanel.add(new ColorGridCell(row, col));
             }
          }
    
          setLayout(new GridBagLayout()); // to center component added
          add(gridPanel);
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private static void createAndShowGui() {
          ColorGrid mainPanel = new ColorGrid();
    
          JFrame frame = new JFrame("ColorGrid");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    @SuppressWarnings("serial")
    class ColorGridCell extends JPanel {
       private static final int PREF_W = 100;
       private static final int PREF_H = 75;
       private final static Color[] COLORS = { Color.red, Color.orange,
             Color.yellow, Color.green, Color.blue, Color.cyan, Color.darkGray,
             Color.magenta, Color.pink };
       private int colorIndex = (int) (Math.random() * COLORS.length);
       private int row;
       private int col;
    
       public ColorGridCell(int row, int col) {
          this.row = row;
          this.col = col;
          setBackground(COLORS[colorIndex]);
    
          addMouseListener(new MouseAdapter() {
             @Override
             public void mousePressed(MouseEvent e) {
                colorIndex++;
                colorIndex %= COLORS.length;
                setBackground(COLORS[colorIndex]);
             }
          });
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       public int getRow() {
          return row;
       }
    
       public int getCol() {
          return col;
       }
    }