gpt4 book ai didi

java - 如何在处理中使用 boolean 数组制作按钮?

转载 作者:行者123 更新时间:2023-11-30 03:44:22 24 4
gpt4 key购买 nike

我正在学习基于 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.lengthi < button.length

关于java - 如何在处理中使用 boolean 数组制作按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com