How to make some buttons interacitve

edited August 2016 in Questions about Code

Hello, i just started using processing and i was wondering how i could make 4 buttons interactive. I want to be able to press a key on the keyboard and make the button do something when that happens.

Im going to use the program i made for an arduino car with bluetooth.

`    void setup(){
      size(500,500);
      background(100,200,200);
    }

    void draw(){
      fill(0,0,0);
      rect(175, 162.5, 125, 62.5);
      rect(175, 250, 125, 62.5);
      rect(25, 250, 125, 62.5);
      rect(325, 250, 125, 62.5);
      fill(255,255,255);
     text("W", 232,195);
     fill(255,255,255);
     text("S", 232,285);
     fill(255,255,255);
     text("A", 80 ,285);
     fill(255,255,255);
     text("D", 380,285);
    }
`
Tagged:

Answers

  • Answer ✓

    Hey

    I borrow some code for this forum. This is an idea of the many possibilities. You can also use controlP5 controls or G4P GUI builder:

    Kf

    //Button dimensions: width and height
    int bW=125;
    int bH=62;
    
    Button b[]; 
    
    
    void setup() {
      size(500,500); 
      rectMode(CORNER);
      textAlign(CENTER, CENTER);
    
      textSize(36);
    
      b = new Button[4];
      b[0] = new Button("W",175, 162.5, bW,bH);
      b[1] = new Button("S",175, 250, bW,bH);
      b[2] = new Button("A",25, 250, bW,bH);
      b[3] = new Button("D",325, 250, bW,bH);
    }
    
    
    void draw() {
      background(0);
    
      for(Button bt : b){
        bt.Draw();
        if(bt.MouseIsOver()==true){
          fill(220,20,20);
          text(bt.getLabel(),width/2,400);
        }
      }
    
    }
    
    
    class Button {
      String label;
      float x;      
      float y;    
      float w;    
      float h;    
    
      // constructor
      Button(String labelB, float xpos, float ypos, float widthB, float heightB) {
        label = labelB;
        x = xpos;
        y = ypos;
        w = widthB;
        h = heightB;
      }
    
      String getLabel(){
        return label;
      }
    
      void Draw() {
        fill(218);
        stroke(141);
        rect(x, y, w, h, 10);
        textAlign(CENTER, CENTER);
        fill(0);
        text(label, x + (w / 2), y + (h / 2));
      }
    
      //ONLY valid when rectMode is set to CORNER !!!
      boolean MouseIsOver() {
        if (mouseX > x && mouseX < (x + w) && mouseY > y && mouseY < (y + h)) {
          return true;
        }
        return false;
      }
    }
    
Sign In or Register to comment.