JavaFX GridPane和NullPointerException

时间:2018-11-23 18:03:46

标签: java javafx

我有一个TileGenerator类。该类生成对象的二维数组(所有对象都有包含图像路径的String image字段),然后将其传递给contoller。控制器使用从数组开始的路径创建新的Image(),并将图像设置为ImageView,将ImageView设置为GridPane。在这里,我得到 NullPointerException -恰好一行 gridPane.add(iv [i] [j],i,j); 我从调试器中知道GridPane为null,但不明白为什么。如何解决?

public class SampleController {
         private Stage stage;

        public void setStage(Stage stage){
            this.stage=stage;
            }
        @FXML
        private AnchorPane ap;
        @FXML
        public TilePane tilePane;
        @FXML
        public GridPane gridPane;    
     TileGenerator generator = new TileGenerator();
     Stage new_game_single = new Stage(); 
     Stage game_single = new Stage();   

public void Game4x4() throws IOException{

            ImageView iv00 = new ImageView();
             ImageView iv01 = new ImageView();
             ImageView iv02 = new ImageView();
             ImageView iv03 = new ImageView();
             ImageView iv04 = new ImageView();
             ImageView iv05 = new ImageView();
             ImageView iv06 = new ImageView();
             ImageView iv07 = new ImageView();
             ImageView iv08 = new ImageView();
             ImageView iv09 = new ImageView();
             ImageView iv10 = new ImageView();
             ImageView iv11 = new ImageView();
             ImageView iv12 = new ImageView();
             ImageView iv13 = new ImageView();
             ImageView iv14 = new ImageView();
             ImageView iv15 = new ImageView();
             ImageView [][] iv = {
                     { iv00, iv01, iv02, iv03},
                     { iv04, iv05, iv06, iv07},
                     { iv08, iv09, iv10, iv11},
                     { iv12, iv13, iv14, iv15}
             };
             generator.TileGenerate4x4();
             Tile tiles[][] = new Tiles[4][4];
             tiles = generator.ShowTiles();

             for(int i=0; i<4; i++) {

                 for(int j=0; j<4; j++) {

                     Image image = new Image(tiles[i][j].getImage());
                    System.out.print(i+","+j+" ...." + tiles[i][j].getImage() +"\n" );

                     iv[i][j].setImage(image);
                     **gridPane.add(iv[i][j],i,j);**

                 }

             }

        }
         @FXML
        private void PlaySingle(){

               Parent root;
                try {
                    root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
                    game_single.setTitle("MEMORY");
                    game_single.setScene(new Scene(root, 1500, 800));

                    new_game_single.close();
                    game_single.show();
                    Game4x4();    
                }    
                    catch (IOException e) {
                    e.printStackTrace();
                }    
   } 
   }

0 个答案:

没有答案