Skip to content

Instantly share code, notes, and snippets.

@lakesare
Last active January 7, 2020 21:58
Show Gist options
  • Save lakesare/5c250576f022262ecc600d81987f75a8 to your computer and use it in GitHub Desktop.
Save lakesare/5c250576f022262ecc600d81987f75a8 to your computer and use it in GitHub Desktop.
Processing button class
class Button {
private float x, y, w, h;
private String label;
private Runnable onClickRunnable;
public Button(float x, float y, float w, float h, String label, Runnable onClickRunnable) {
this.x = x; this.y = y; this.w = w; this.h = h;
this.font = createFont("Tahoma", 13, true);
this.label = label;
this.onClickRunnable = onClickRunnable;
}
public void draw() {
runActions();
drawRectangle();
drawText();
}
private void drawRectangle() {
// not setting cursor(HAND), because processing makes it ugly
if (isMouseOver()) {
fill(212, 218, 240, 40);
} else {
fill(212, 218, 240, 20);
}
noStroke();
rect(x, y, w, h, 3);
}
private void drawText() {
fill(200);
noStroke();
textFont(font);
textAlign(CENTER, CENTER);
text(label, x + w/2, y + h/2);
}
private void runActions() {
if (mousePressed && isMouseOver()) {
onClickRunnable.run();
}
}
public boolean isMouseOver() {
boolean inX = mouseX >= x && mouseX <= x + w;
boolean inY = mouseY >= y && mouseY <= y + h;
return inX && inY;
}
}
Button myButton = new Button(
x, y,
buttonW, buttonH,
"Press me",
new Runnable() { public void run() { println("Hi babe"); } }
);
void setup() {
size(600, 600, P3D);
pixelDensity(2);
noFill();
}
void draw() {
myButton.draw();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment