Wish my first post was something grander, but alas... ;)
I am prototyping a framework for a grid-based GUI. Right now I'm trying to get hover/click/toggle states happening.
Hovering and clicking was fine, but I started to run into a cascading world of trouble when I tried to implement a
toggle on/off state for individual cells.
At this point it's almost working... but the
"click and drag" behaviour you see is
not intended. There is also supposed to be
distinct hover states for cells that are toggled on vs. off.
And, my very limited programming instincts are telling me that it's ugly, inefficient code. Should I be using the MouseListener approach for individual objects, instead of mousePressed? (it's a bit over my head right now, but if that's the only way to get this happening properly, I'll put my focus to learning it)
I can provide more detail about what I have tried so far and what happened, etc., but I suspect it will be fairly obvious to the more experienced eye what's at fault:
Tile[][] tiles;
int gridSize = 10;
int tileSize = 40;
int togInit = 0;
void setup() {
size (400, 400);
background (255);
smooth();
tiles = new Tile[gridSize][gridSize];
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
tiles[i][j] = new Tile((i*40), (j*40), tileSize, tileSize, togInit);
}
}
}
void draw() {
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
tiles[i][j].update();
tiles[i][j].display();
}
}
}
Tile class:
class Tile {
int tx, ty;
int tw, th;
color tileCol = color(255);
color togCol = color(50, 0, 0);
color hoverCol = color(100, 200, 100);
color hoverTog = color(50, 0, 0, 50);
color clickCol = color(150, 200, 150);
int toggleState;
boolean hover = false;
boolean click = false;
// Here be constructors
Tile (int itx, int ity, int itw, int ith, int tempTog) {
tx = itx;
ty = ity;
tw = itw;
th = ith;
toggleState = tempTog;
}
// Check hover and click states
void update() {
if (mouseX >= tx && mouseX <= tx+tileSize &&
mouseY >= ty && mouseY <= ty+tileSize) {
hover = true;
if (mousePressed==true && click==false) {
if (toggleState==0) {
toggleState = 1;
} else if (toggleState==1) {
toggleState = 0;
}
click = true;
} else if (mousePressed==false){
click = false;
}
} else {
hover = false;
}
}
void display() {
if ((hover==false) && (click==false)) { // Hover, NO Click
if (toggleState==1) { // ... Toggle ON
fill (hoverTog);
} else if (toggleState==0) { // ... Toggle OFF
fill(hoverCol);
}
} else if ((hover==false) && (click==true)) { // Hover and Click
fill (clickCol);
} else if (toggleState==1) { // NO Hover, Toggle ON
fill(togCol);
} else { // Default
fill(tileCol);
}
stroke (0);
rect(tx, ty, tw, th);
}
}
Thank you so much in advance for any troubleshooting/refinements!