如何在 Processing 2.2.1 中制作按钮 class 并打印按钮标签

how to make a button class and print the button label in Processing 2.2.1

我的代码有问题。如果我点击按钮,结果是每当我点击按钮时它会打印很多字符,就像第一个按钮是 "H" 结果会像 "HHHHHHH"

我正在尝试使用 leap motion 设备作为键盘来制作虚拟键盘。如果我进行搜索和选择,按钮颜色就会改变。

color currentcolor;
RectButton rect1, rect2;
boolean locked = false;
void setup() {
  //set up window
  size(200, 200);
  color baseColor = color(102, 102, 102);
  currentcolor = baseColor;

  int x = 30;
  int y = 100;
  int size = 50;
  color buttoncolor = color(153, 102, 102);
  color highlight = color(102, 51, 51); 
  rect1 = new RectButton(x, y, size, buttoncolor, highlight);
  // Define and create rectangle button #2
  x = 90;
  y = 100; 
  size = 50;
  buttoncolor = color(153, 153, 153);
  highlight = color(102, 102, 102); 
  rect2 = new RectButton(x, y, size, buttoncolor, highlight);
}
void draw() {
  background(currentcolor);
  stroke(255);
  update(mouseX, mouseY);
  rect1.display();
  rect2.display();
}
void update(int x, int y) {
  if(locked == false) {
    rect1.update();
    rect2.update();
  } else {
    locked = false;
  }
  if(mousePressed) {
    if(rect1.pressed()) {            //ON button
      currentcolor = rect1.basecolor;
      print("H");
    } else if(rect2.pressed()) {    //OFF button
      currentcolor = rect2.basecolor;
      print("L");
    }
  }
}
class Button {
  int x, y;
  int size;
  color basecolor, highlightcolor;
  color currentcolor;
  boolean over = false;
  boolean pressed = false;   
  void update() 
  {
    if(over()) {
      currentcolor = highlightcolor;
    } else {
      currentcolor = basecolor;
    }
  }
  boolean pressed() 
  {
    if(over) {
      locked = true;
      return true;
    } else {
      locked = false;
      return false;
    }    
  }
  boolean over() 
  { 
    return true; 
  }
  void display() 
  { 
  }
}
class RectButton extends Button {
  RectButton(int ix, int iy, int isize, color icolor, color ihighlight) 
  {
    x = ix;
    y = iy;
    size = isize;
    basecolor = icolor;
    highlightcolor = ihighlight;
    currentcolor = basecolor;
  }
  boolean over() 
  {
    if( overRect(x, y, size, size) ) {
      over = true;
      return true;
    } else {
      over = false;
      return false;
    }
  }
  void display() 
  {
    stroke(255);
    fill(currentcolor);
    rect(x, y, size, size);
  }
}
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;
  }
}

问题是您在 draw() 循环中检查 mousePressed 的状态,所以每秒检查 60 次。鼠标按下可能会记录不止一帧,因此 if(mousePressed) 每帧多次为真。

我会这样做:

使用 mousePressed() 函数切换布尔值 ON 标志:

boolean ON=false; // initial setting.
void mousePressed() {
  ON = !ON;
}

变化:

if(mousePressed) {...} 

if(ON) {...}
ON=false;