G4P - Checkbox grid

OK this is a fairly sophisticated example because it has a class to encapsulate a 2D grid of checkboxes. The advantage is that the class does all the hard work in creating the checkboxes and allows for more than one grid (the example has 2 grids).

Try out the example and if you have questions then I will try and answer them.

import g4p_controls.*;

// Demonstration of a 2D grid of checkboxes. The size of the grid is user defineable.
// 
CheckboxGrid cbg0, cbg1;


void setup() {
  size(600, 400);
  G4P.messagesEnabled(false);
  cbg0 = new CheckboxGrid(this, 20, 50, 10, 8, 8);
  cbg1 = new CheckboxGrid(this, 400, 250, 0, 3, 5);
}

void draw() {
  background(200, 200, 255);
}

/*
This class encapsulates a 2D array of checkboxes
 */
public class CheckboxGrid {

  final GCheckbox [][] grid;
  final int nbrRows, nbrCols;

  /*
   Use this constructor to create the grid
   */
  CheckboxGrid(PApplet papp, 
    int left, int top, // top left corner of box encompassing all checkboxes
    int gutter, // The spacing between each row and column
    int nbrRows, int nbrCols // number of rows and columns in the grid
    ) {
    this.nbrRows = nbrRows;
    this.nbrCols = nbrCols;
    grid = new GCheckbox[nbrRows][nbrCols];
    int colSpace = 20 + gutter;
    int rowSpace = 16 + gutter;
    for (int row = 0; row < nbrRows; row ++) {
      for (int col = 0; col < nbrCols; col ++) {
        GCheckbox cbx = new GCheckbox(papp, col * colSpace + left, row * rowSpace + top, 20, 10);
        cbx.tagNo = row * 10000 + col;
        cbx.tag = "Box [row " + row + ",  col " + col +"]";
        cbx.addEventHandler(this, "handleEvents");
        grid[row][col] = cbx;
      }
    }
  }

  /*
   Probably don't need this since you will be checking the state using getState(...)
   in the main code
   */
  public void handleEvents(GCheckbox source, GEvent event) {
    String action = event == GEvent.SELECTED ? " was SELECETED " : " was DESELECETED ";
    println(source.tag + action + "\t" + millis());
  }

  /*
   Get the state (true / false) of a checkbox based on its position in the grid.
   If the user specifies a position outside the grid it returns false.
   */
  public boolean getState(int row, int col) {
    if (row >=0 && row <= nbrRows && col >= 0 && col <= nbrCols) {
      return grid[col][row].isSelected();
    }
    return false; // row, col is not inside grid
  }

  /*
   Allows the user to set the state of a particular checkbox instead of clicking on it
   If the user specifies a position outside the grid it does nothing.
   */

  public void setState(int row, int col, boolean state) {
    if (row >=0 && row <= nbrRows && col >= 0 && col <= nbrCols) {
      grid[row][col].setSelected(state);
    }
  }
}
2 Likes