【问题标题】:How to make buttons with a boolean array in Processing?如何在处理中使用布尔数组制作按钮?
【发布时间】:2014-09-29 19:18:08
【问题描述】:

我正在学习在基于 Java 的环境“处理”中的编程课程。一项任务是编写一个显示 3 个按钮(黑色)的程序。单击按钮时,该按钮应更改为另一种颜色(灰色)。我们需要使用 boolean[] 数组。我的代码如下:

boolean[] button = new boolean[3];

void setup(){
    size(300,300);
    button[0] = false;
    button[1] = false;
    button[2] = false;
}

void draw(){
    int x = (width/(button.length+1));
    int y = height/2;
    int ellipseSize = 50;
    int radius = ellipseSize/2;
    background(255);
    noStroke();
    fill(0);
    for(int i = 1; i <= button.length; i++){
        ellipse(i*x, y, ellipseSize, ellipseSize);
    }
} 

//shifting array values upon mouse pressing
void mousePressed(){


    int x = (width/(button.length+1));
    int y = height/2;
    int ellipseSize = 50;
    int radius = ellipseSize/2;

    for(int i = 1; i <= button.length; i++){
        button[i] = !button[i];
        if (mouseX > i*x-radius && mouseX < i*x+radius && mouseY > y-radius && mouseY < y+radius){
            if (button[i]){
                fill(150);
            }
        }
        else {
            fill(0);
        }
        ellipse(i*x, y, ellipseSize, ellipseSize);
    } 
}

我收到一条错误消息“ArrayIndexOutOfBoundsException: 3”。有人可以帮忙吗?

【问题讨论】:

  • 在大多数编程语言中,数组从0 开始,而不是像现实生活中的1。您在 setup 函数中已经做到了这一点,但在您的 for 循环中却没有,它从 1 循环到 3 而不是 0 到 2。

标签: java arrays button boolean processing


【解决方案1】:

您收到错误ArrayIndexOutOfBoundsException: 3,因为您尝试访问非法索引。在 Java 和大多数编程语言中,数组从 0 开始。 因此,在您的 for 循环中,您需要将 i &lt;= button.length 更改为 i &lt; button.length

【讨论】:

    【解决方案2】:

    由于在大多数编程语言中很少有人提到数组从索引0 开始,最后一个索引在button.length - 1,因此您需要更改for 循环或button[i] 调用。

    但要完成您的按钮,您需要了解有关处理的更多信息。您的绘图函数被重复调用(取决于您的 fps),并且您始终使用 background 函数清除草图。然后将填充颜色设置为黑色并绘制三个圆圈。如果您在鼠标事件中更改fill,它有时可能会起作用(如果您在绘制圆圈的同时单击),但这是非常糟糕的方法。

    您需要根据button 数组在draw 函数中设置fill:

    for(int i = 1; i <= button.length; i++){ //good boundaries for drawing but not for array
        if(button[i-1]) {                    //for array you need correct index
          fill(0);
        }else{
          fill(150);
        }
        ellipse(i*x, y, ellipseSize, ellipseSize);
    }
    

    当然,将鼠标事件更改为仅检查是否单击了按钮并将此信息存储在 button 数组中以供下一次绘制。

     for(int i = 1; i <= button.length; i++){   //your old boundaries
        if (mouseX > i*x-radius && mouseX < i*x+radius && mouseY > y-radius && mouseY < y+radius){
          button[i-1] = !button[i-1];          //updated index
        } 
     }
    

    【讨论】:

      【解决方案3】:

      改变

      i <= button.length
      

      到

      i < button.length
      

      如果数组的长度是 3,那么 button[2] 就是最后一个元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 1970-01-01
        • 2016-04-05
        • 2021-07-06
        • 1970-01-01
        • 2017-07-10
        • 2011-10-09
        相关资源
        最近更新 更多