G4P - Checkbox grid

here the check boxes get shown in an 2D Array / grid - see tutorial “two-dimensional arrays”

probably there are simpler ways to do this…

somehow rows and cols are swapped in the array…???

Chrisir


// somehow rows and cols are swapped in the array...???


import g4p_controls.*;

String[][] shopping_list = {
  {"Apples", "Pears", "Oranges", "Bananas"}, // Row 1 has 4 boxes
  {"Lamb", "Beef", "Pork", "Buscuits"}, // Row 2 has 4 boxes
  {"Salt", "Pepper", "c1", "c2"}, // Row 3 
  {"Jam", "Marmalade", "Tomatos", "c3"}, // Row 4 
  {"Wheatabix", "Butter", "Marmite", "Pizza"}   // Row 5 has 4 boxes
};

String[][] result = {
  {"_", "_", "_", "_"}, // Row 1 has 4 boxes
  {"_", "_", "_", "_"}, // Row 2 has 4 boxes
  {"_", "_", "_", "_"}, // Row 3 
  {"_", "_", "_", "_"}, // Row 4 
  {"_", "_", "_", "_"}  // Row 5 has 4 boxes
};

HashMap<String, Integer>  hmX= new HashMap<String, Integer>();
HashMap<String, Integer>  hmY= new HashMap<String, Integer>();

void setup() {
  size(1600, 300);
  G4P. messagesEnabled(false);
  makeShoppingList();
  for (int row = 0; row < result.length; row ++) {
    for (int col = 0; col < result[row].length; col ++) {
      result[row][col]="_";
    }
  }
}

void makeShoppingList() {
  GCheckbox cbx;
  for (int row = 0; row < shopping_list.length; row ++) {
    for (int col = 0; col < shopping_list[row].length; col ++) {
      cbx = new GCheckbox(this, col * 100 + 20, row * 25 + 30, 90, 20, shopping_list[row][col]);
      cbx .addEventHandler(this, "shoppingListChange");
      //println(shopping_list[row][col]); 
      hmX.put(shopping_list[row][col], row); 
      hmY.put(shopping_list[row][col], col);
    }
  }
}

void shoppingListChange(GCheckbox source, GEvent event) {
  println(source.getText() );

  String action = event == GEvent.SELECTED ? " ADDED " : " REMOVED ";

  boolean state =  event == GEvent.SELECTED ? true : false;

  // We can also access values by their key
  int row = hmX.get(source.getText() );
  int col = hmY.get(source.getText() );

  if (state)
    result[row][col] = "1";
  else result[row][col] = "_";

  println(source.getText() + action + "\t" + millis());
}

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

  fill(0); 
  for (int row = 0; row < result.length; row ++) {
    for (int col = 0; col < result[row].length; col ++) {
      text (  result[row][col], 
        col * 100 + 620, row * 25 + 30);
    }
  }
}
//

1 Like