我试图在JFrame中绘制随机大小的正方形,但JFrame变成空白。
我正在尝试恢复旧代码,并在进行了一些挖掘之后,在这里,我认为问题可能出在我的构造函数中?我知道代码可以在某一时刻起作用,并希望有人可以将我指向正确的方向
变量:
int sizeBig = 150;
int canvasW = 1300;
int canvasH = 750;
Random rand = new Random();
int initialS = 1;
int numberS = 40;
int smallsizeVAR = sizeBig / 3;
int border1=0;
/* Black */
String color1 = "#000000";
String color2 = "#000000";
String color3 = "#000000";
String color4 = "#000000";
String color5 = "#000000";
String color6 = "#000000";
String color7 = "#000000";
String color8 = "#000000";
String colorBG= "#ffffff";
我绘制正方形的代码:
public void paint(final Graphics g) {
g.setColor(Color.decode(colorBG));
g.fillRect(0, 0, canvasW, canvasH);
// while
while (initialS <= numberS) {
final int randX = rand.nextInt(canvasW + sizeBig) + (0 - sizeBig);
final int randY = rand.nextInt(canvasH + sizeBig) + (0 - sizeBig);
// size random
final int sizeRAND = rand.nextInt(((sizeBig + 1) - smallsizeVAR) + 1) + smallsizeVAR;
// end size rnd
// rand color 1-4
final String[] arr = { color2, color3, color4, color5, color6, color7, color8 };
final Random random = new Random();
final int select = random.nextInt(arr.length);
g.setColor(Color.decode(arr[select]));
g.fillRect(randX, randY, sizeRAND, sizeRAND);
g.setColor(Color.decode(colorBG));
g.fillRect(randX + (sizeRAND - ((4 * sizeRAND) / 5)) / 2, randY + (sizeRAND - ((4 * sizeRAND) / 5)) / 2,
((4 * sizeRAND) / 5), (4 * sizeRAND) / 5);
initialS++;
if (initialS == numberS) {
g.setColor(Color.decode(arr[select]));
g.fillRect(canvasW / 8, canvasW / 8, (3 * sizeBig) / 2, (3 * sizeBig) / 2);
}
}
// end while
}
我的构造函数:
// The constructor follows:
public GraphicsDemo_noborders() {
setTitle("Programatic Art");
setSize(canvasW, canvasH);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
主要:
public static void main(String args[]) {
GraphicsDemo_noborders demo = new GraphicsDemo_noborders();
}