/* keypad.pde Written by Justin Hsia Implement a phone keypad. Clicking "C" will clear the entered numbers. */ // variable for dialed keys String dialed = ""; // variables related to keypad int boardX = 100; // x-position of upper-left corner of board int boardY = 100; // y-position of upper-left corner of board int keySize = 50; // size of keys (including border) int border = 2; // border around keys int rows = 4; // number of rows in our grid int cols = 3; // number of columns in our grid char[] keypad = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#'}; // variables related to the CLEAR button int clearX = 150; // x-position of upper-left corner of CLEAR button int clearY = 300; // y-position of upper-left corner of CLEAR button void setup() { size(500, 500); textSize(40); // make the text bigger } void draw() { background(204); textAlign(CENTER); // DRAW THE CLEAR BUTTON BACKGROUND fill(0); rect(clearX, clearY, keySize, keySize); // DRAW THE CLEAR BUTTON if ( overClear() ) { // hover detection over Clear button fill(255, 255, 98); // yellow button if hovering over } else { fill(255); // white button otherwise } rect(clearX+border, clearY+border, keySize-2*border, keySize-2*border); // DRAW THE CLEAR BUTTON LABEL fill(255, 0, 0); // red text text("C", 175, 340); // DRAW THE KEYPAD BACKGROUND fill(0); // black fill rect(boardX, boardY, cols*keySize, rows*keySize); // DRAW THE KEYPAD int j = 0; while (j < rows) { // # of rows int i = 0; while (i < cols) { // # of columns fill(255); // white keys rect(boardX+border+i*keySize, boardY+border+j*keySize, keySize-2*border, keySize-2*border); fill(0); // black text text(keypad[i+3*j], boardX+keySize/2+i*keySize, boardY+j*keySize+40); i = i + 1; } j = j + 1; } // DISPLAY DIALED KEYS textAlign(LEFT); text(dialed, boardX, clearY+100); } // currently prints "Cleared!" to the console when CLEAR button is clicked void mousePressed() { // DETECT CLEAR CLICK if ( overClear() ) { dialed = ""; //println("Cleared!"); } // DETECT GRID CLICK if ( (mouseX >= boardX) && (mouseX <= boardX+cols*keySize) && (mouseY >= boardY) && (mouseY <= boardY+rows*keySize) ) { // extract grid coordinates from mouse click int gridX = int( (mouseX-boardX)/keySize ); int gridY = int( (mouseY-boardY)/keySize ); dialed = dialed + keypad[gridY*cols+gridX]; } } // returns true if the mouse is currently over the CLEAR button boolean overClear() { return (mouseX >= clearX) && (mouseX <= clearX+keySize) && (mouseY >= clearY) && (mouseY <= clearY+keySize); }