// processing IDE 3.5.3 // button tutorial // http://kll.engineering-news.org/kllfusion01/articles.php?article_id=166 // we have already a simple class for ONE Button, // but there is one step more, what brings it closer to the objects / elements you might know from some libraries. // a button what can draw itself ( no need to call it in/from draw() ) // also has its own key and mouse functions registered // but all this also has its disadvantages, besides the overhead, // if you not need it anymore how you stop it? you need to make a add show / hide method ... Button myButton = new Button(this, 100, 100, 80, 30, false, "text", 0); // make a button of type class Button void setup() { size(300, 300); } void draw() { background(200, 200, 0); } void keyPressed() { // test button disable if ( key == 's' ) myButton.setShow(true); if ( key == 'h' ) myButton.setShow(false); } public class Button { //________________________________________ begin class BUTTON PApplet pa; int x, y, w, h, id; boolean click=false, sel; String atext; boolean showit=true; Button(PApplet pa, int x, int y, int w, int h, boolean sel, String atext, int id) { this.pa = pa; this.x = x; this.y = y; this.w = w; this.h = h; this.sel = sel; this.atext = atext; this.id = id; pa.registerMethod("draw", this); pa.registerMethod("mouseEvent", this); pa.registerMethod("keyEvent", this); } public void draw() { if ( this.showit ) { if (this.sel) fill(0, 200, 0); //___________________ ON OFF fill color else fill(0, 0, 200); if (this.over()) stroke(200, 0, 200); //_______________ hover stroke color else stroke(0, 200, 200); strokeWeight(3); rect(this.x, this.y, this.w, this.h); //__________________ button area as rectangle noStroke(); //____________________________________________ button text ( here only one ) fill(200); text(this.atext, this.x + 10, this.y + this.h - 10); } } public void setShow(boolean set) { this.showit = set; } public boolean over() { return (mouseX > this.x && mouseX < this.x + this.w && mouseY > this.y && mouseY < this.y + this.h); } public void mouseEvent(MouseEvent m) { // from @quark if ( this.over() ) { switch (m.getAction()) { case MouseEvent.PRESS: this.sel = !this.sel; //________________________________ toggle memory break; case MouseEvent.RELEASE: // break; } } } // the keyboard input we not use, just prepare public void keyEvent(KeyEvent e) { // from @quark int keyCode = e.getKeyCode(); char keyChar = e.getKey(); int keyID = e.getAction(); if (keyID == KeyEvent.PRESS ) keyPressedProcess(keyCode, keyChar); if (keyID == KeyEvent.RELEASE) keyReleasedProcess(keyCode, keyChar); } // here we use .sel like a focus for test protected void keyPressedProcess(int keyCode, char keyChar) { if ( this.sel ) println("Button: "+this.id+" keyPressed, key "+keyChar); } protected void keyReleasedProcess(int keyCode, char keyChar) { if ( this.sel ) println("Button: "+this.id+" keyPressed, key "+keyChar); } } //_____________________________________________________ end class