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 › buttons with eventlisteners
Page Index Toggle Pages: 1
buttons with eventlisteners (Read 417 times)
buttons with eventlisteners
Jun 18th, 2007, 11:05pm
 
I've been toying around with the excellent controlP5 library for some time now, but have come to the conclusion that I want to create my own gui elements.

I've built upon the Button examples and created a small sketch:

Code:

ArrayList buttons = new ArrayList();

boolean locked = false;

color c = color(0,0,0);

void setup() {
size(400,400);
background(0);

buttons.add( new Button(80, 100, 100, 20) );
buttons.add( new Button(220, 100, 100, 20) );
}

void draw() {

background(c);

// draw buttons
if (buttons.size() > 0) {
for (int i=0; i < buttons.size(); i++) {
Button b = (Button) buttons.get(i);
b.display();
b.update();
}
}

// how can I call randomBG() using the left button?
//randomBG();

// how can I call blackBG() using the right button?
//blackBG();

}

void whiteBG() {
c = color(255,255,255);
}

void blackBG() {
c = color(0,0,0);
}



// Button
class Button {

int x, y;
int w, h;
color basecolor, highlightcolor;
color currentcolor;
boolean over = false;
boolean pressed = false;

Button (int _x, int _y, int _w, int _h) {
x = _x;
y = _y;
w = _w;
h = _h;

basecolor = color(153, 153, 153);
highlightcolor = color(102, 102, 102);
currentcolor = basecolor;
}

void display()
{
noStroke();
fill(currentcolor);
rect(x, y, w, h);
}


void update()
{
if(over()) {
currentcolor = highlightcolor;
}
else {
currentcolor = basecolor;
}
}

boolean over()
{
if( overRect(x, y, w, h) ) {
over = true;
return true;
}
else {
over = false;
return false;
}
}


boolean pressed()
{
if(over) {
locked = true;
return true;
}
else {
locked = false;
return false;
}
}

boolean overRect(int x, int y, int width, int height) {
if (mouseX >= x && mouseX <= x+width &&
mouseY >= y && mouseY <= y+height) {
return true;
}
else {
return false;
}
}
}



I know the above problem is a simple task that could be solved differently, but I want to try the most elegant way using event listeners. Unfortunately, even after reading through the Java Tutorials on this topic I haven't managed to wrap my head around the concept of listeners.
So far I've learned it's about implementing and adding ActionListerens, but I'm afraid I have no clue where to start and place these things in my code.

Does anyone have a hint on how to I should begin to rewrite the code

Thanks so much.
Greg
Page Index Toggle Pages: 1