We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › constants and object arrays
Page Index Toggle Pages: 1
constants and object arrays (Read 447 times)
constants and object arrays
Jul 5th, 2008, 2:13am
 
I'm trying to write a program that would write 12 boxes on the window and notify me which one i'm on. I can't seem to get the syntax right, I don't know how to make an array of objects, nor do I know how to define constants...here's the code i have so far (it's not done)


import processing.serial.*;

class MRect
{
 int x;
 int y;
 int height;
 int width;

 MRect(int _x, int _y, int _w, int _h) {
   x = _x;
   y = _y;
   width = _w;
   height = _h;
 }

 boolean isMouseOver(){
   return (mouseX >= x) && (mouseX < x + width) && (mouseY >= y) && (mouseY > y + height);
 }

 void draw() {

 }
}

Serial port;
MRect rects[12];
int num_rects = 12;

#define WIDTH 66;
#define HEIGHT 66;

void setup()
{
 size(792, 66);
 frameRate(10);
 port = new Serial(this, Serial.list()[0], 9600);

}

boolean mouseOverRect()
{
 return ((mouseX >= 50)&&(mouseX <= 150)&&(mouseY >= 50)&(mouseY <= 150));
}

void draw()
{
 background(#222222);

 fill(#666660);         // change color

 for(int i=0;i<num_rects;i++){
   rects[i] = new MRect(WIDTH * i,0,WIDTH,HEIGHT);
 }
}

Re: constants and object arrays
Reply #1 - Jul 5th, 2008, 6:24am
 
I tweaked your code a bit (added a visual cue)

Quote:


class MRect {
 int x;
 int y;
 int h;
 int w;
 color bgColor;

 MRect(int _x, int _y, int _w, int _h, color _bgColor) {
   x = _x;
   y = _y;
   w = _w;
   h = _h;
   bgColor = _bgColor;
 }

 boolean isMouseOver(){
   return (mouseX > x) && (mouseX < x + w) && (mouseY > y) && (mouseY < y + h);  
 }
 
 void setBGColor(color _bgColor){
   bgColor = _bgColor;
 }
 
 void create(){
   fill(bgColor);
   rect(x, y, w, h);
 }
}

final int NUMBER_RECTS = 12;
MRect[] rects = new MRect[NUMBER_RECTS];

int rectWidth =  66;
int rectHeight =  rectWidth;

void setup() {  
 size(793, 67);  
 
 for(int i=0;i<rects.length;i++){
   rects[i] = new MRect(rectWidth * i,0,rectWidth,rectHeight,color(200, 200, 255));  
 }
}  


void draw() {  
 background(#222222);  

for(int i=0;i<rects.length;i++){
   if (rects[i].isMouseOver()){
     rects[i].setBGColor(color(255, 170, 0));
     println(rects[i]);
   } else {
      rects[i].setBGColor(color(200, 200, 255));
   }
    rects[i].create();  
 }
}


Page Index Toggle Pages: 1