2017-04-19 51 views
0

我写了一些代码像下面试图显示一个20图像的数组,但只得到最后一个图像显示。我很困惑,期待你的帮助!使用for循环唯一diaplays最后的图像

String []img={"a.png","b.png","c.png"...20 more}; 
for(int x=0;x<20;x++) 
    { 
     images[x]=new Image(img[x]); 
     views[x]=new ImageView(images[x]); 


//put the images in the buttons on GridPane 
     for(int i=0;i<4;i++){//row 
      for(int j=0;j<5;j++){//column 
       buttons[5*i+j]=new Button(); 
       buttons[5*i+j].setGraphic(new ImageView(images[x])); 
       gridPane.add(buttons[5*i+j], j, i); 
       buttons[5*i+j].setPrefHeight(120); 
       buttons[5*i+j].setPrefWidth(120); 
      } 
     } 

    } 

回答

0

您将所有三个循环嵌套在一起。所以,在伪代码:

for each of the 20 images: 
    for each row: 
     for each column: 
      create a button showing the image in the row/column 

或等价:

for each of the 20 images: 
    for each cell: 
     create a button showing the image in the cell 

所以在最外层循环的第一次迭代,您填写的按钮电网,无不呈现出第一张图像。在最外层循环的第二次迭代中,用网格填充网格,每个按钮都显示第二个图像。等等。

因此,网格中的每个单元格都有20个按钮:所有这些按钮都将放在彼此的顶部,只添加最后一个按钮。

你只需要在每个单元一个按钮:

String[] img = {"a.png","b.png","c.png" /*...20 in totalv*/}; 

for(int x = 0 ; x < 20 ; x++) { 
    images[x]=new Image(img[x]); 
    views[x]=new ImageView(images[x]); 
} 

//put the images in the buttons on GridPane 
for(int i = 0 ; i < 4 ; i++) { //row 
    for(int j = 0 ; j < 5 ; j++) { //column 
     int index = 5 * i + j 
     buttons[index]=new Button(); 
     buttons[index].setGraphic(views[index]); 
     gridPane.add(buttons[index], j, i); 
     buttons[index].setPrefHeight(120); 
     buttons[index].setPrefWidth(120); 
    } 
} 
+0

你这么cooool! – Yong