我正在学习基于 Java 的环境“Processing”中的编程类(class)。其中一项作业是编写一个显示 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”。有人可以帮忙吗?
最佳答案
您收到错误ArrayIndexOutOfBoundsException: 3
因为您试图访问非法索引。在 Java 和大多数编程语言中,数组从 0
开始。 。
因此,在 for 循环中,您需要更改 i <= button.length
至i < button.length
关于java - 如何在处理中使用 boolean 数组制作按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107220/