Search code examples
javajavafximageviewtilegridpane

JavaFX - Is there a method to print one image multiple times using imageview?


Given the code below, i'm trying to print out a single image (stored in variable 'image') multiple times. Any suggestions as to how i'd go about doing this? Any information would be useful.

    Image image = new Image("tileset.png");
    ImageView tileset = new ImageView();
    tileset.setImage(image);

    Rectangle2D viewport1 = new Rectangle2D(0,16,16,16); //(selected pixels)
    tileset.setViewport(viewport1);
    int length = 40, width= 40;  // declare size of array (print 40x40)

    // loop through grid, fill every tile with image 'image'. 
    // currently only fills position (40,40) with the image. 
    for(int y = 0; y < length; y++)
    {
        for(int x = 0; x < width; x++)
        {
            GridPane.setConstraints(tileset,x,y);
        }
    }


    root.getChildren().add(tileset);

Solution

  • The method GridPane.setConstraints(tileset,x,y) does not add a child to gridpane, it just sets the indices of child node. In order to add it to gridpane you should call root.getChildren().add(tileset) every time in the loop with a new ImageView.

    Image image = new Image("tileset.png");
    
    Rectangle2D viewport1 = new Rectangle2D(0,16,16,16); //(selected pixels)
    int length = 40, width= 40;  // declare size of array (print 40x40)
    
    // loop through grid, fill every tile with image 'image'. 
    // currently only fills position (40,40) with the image. 
    for(int y = 0; y < length; y++)
    {
        for(int x = 0; x < width; x++)
        {
            ImageView tileset = new ImageView(image);
            tileset.setViewport(viewport1);
    
            GridPane.setConstraints(tileset,x,y);
            root.getChildren().add(tileset);
        }
    }