Hello. Perhaps this little piece of code will help you on your way. It is my very basic implementation of buttons, that I threw together when I needed a way to interactively toggle the effects for my sketches.
Quote:abstract class AbstractButton {
protected boolean mouseOver = false, mouseOut = false, mouseDown = false;
//AbstractButton() { }
abstract public boolean mouseOver();
public boolean mouseDown() {
if ( (mousePressed) && (mouseButton == LEFT) ) return true;
else return false;
}
public void update() {
if (mouseOut == true) mouseOut = false;
if (mouseOver()) {
if (mouseOver == false) onMouseOver();
mouseOver = true;
}
else {
if (mouseOver == true) mouseOut = true;
mouseOver = false;
}
if (mouseOut) onMouseOut();
if (mouseDown() && !mouseDown) {
if ( mouseOver() ) onClick();
mouseDown = true;
}
else if (mouseDown && !mouseDown()){
mouseDown = false;
}
onUpdate();
}
public void onClick() { }
public void onMouseOver() { }
public void onMouseOut() { }
public void onUpdate() { }
abstract public void render();
};
class SquareButton extends AbstractButton {
protected PVector pos;
protected float myWidth,myHeight;
protected final int fillColorActive = 0xFF00AAFF;
protected final int fillColorPassive = 0xFF33AAAA;
protected int fillColor = fillColorPassive;
SquareButton(float _x,float _y,float _w,float _h) {
myWidth = _w; myHeight = _h;
pos = new PVector(_x,_y);
}
public boolean mouseOver() {
if ( (mouseX > (pos.x-myWidth/2.0)) && (mouseX < (pos.x+myWidth/2.0)) && (mouseY > (pos.y-myHeight/2.0)) && (mouseY < (pos.y+myHeight/2.0)) ) return true;
else return false;
}
public void onClick() {
println("onClick fired");
}
public void onMouseOver() {
println("mouseOver fired");
fillColor = fillColorActive;
}
public void onMouseOut() {
println("mouseOut fired");
fillColor = fillColorPassive;
}
public void render() {
pushStyle();
smooth();
fill(fillColor);
rectMode(CENTER);
rect(pos.x,pos.y,myWidth,myHeight);
popStyle();
}
};
Then you use it like this:
Quote:SquareButton b;
void setup() {
size(640,480,P2D);
b = new SquareButton(width-80,height-60,120,80);
}
void draw() {
b.update();
b.render();
}