2017-04-19 6 views
0

次のようなコードを書いて、20個の画像の配列を表示しようとしましたが、最後の画像しか表示されませんでした。私は大きな混乱とあなたの助けを楽しみにしています!forループのみを使用すると、最後の画像が表示されます

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

3つのループを相互に入れ子にしました。だから、擬似コードで:

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 

だから、最も外側のループの最初の反復では、すべての最初の画像を表示、ボタンでグリッドを埋めます。一番外側のループの2番目の反復では、グリッドにはボタンで2つ目の画像が表示されます。等々。

グリッド内の各セルには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

関連する問題