我目前正在尝试创建一个场景,其中每次单击JPanel时,它每次都会更改不同的颜色。例如,我不想单击洋红色正方形并再次获得洋红色正方形。
Color newColor = null;
Color[] colorArr = {Color.YELLOW, Color.MAGENTA, Color.BLACK,new Color (0x964B00),new Color (0xB57EDC)};
int ranNum = generator.nextInt(5);//generator is a .Random Object
switch (ranNum) {
case 0:
newColor = colorArr[0];
break;
case 1:
newColor = colorArr[1];
break;
case 2:
newColor = colorArr[2];
break;
case 3:
newColor = colorArr[3];
break;
case 4:
newColor = colorArr[4];
break;
}
最佳答案
您应该定义一个保存旧颜色值的全局变量。
int oldNum;
Color[] colorArr = {Color.YELLOW, Color.MAGENTA, Color.BLACK,new Color (0x964B00),new Color (0xB57EDC)};
void changeColor(){
Color newColor = null;
int ranNum;
do{
ranNum = generator.nextInt(5);//generator is a .Random Object
}while(oldNum == ranNum);
oldNum = ranNum;
newColor = color[ranNum];
}
关于java - 每次单击时如何获得不同的颜色?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49313504/