Search code examples
javajavafxjavafx-11

How to style multiple ImageViews to not violate DRY in JavaFX11


Is there a way to style multiple ImageViews and similar? For example, I have this code:

Image pic1 = new Image(getClass().getResourceAsStream("/pic1.png"));
ImageView picView1 = new ImageView(pic1);
picView1.setFitHeight(PIC_SIZE);
picView1.setPreserveRatio(true);
picView1.setSmooth(true);

Image pic2 = new Image(getClass().getResourceAsStream("/pic2.png"));
ImageView picView2 = new ImageView(pic2);

...

I would like to change the SIZE on all images, there are over 10 images. Could I create a Group and add all views to it and by that target all of the Objects to manipulate? Very new to JavaFX (11).


Solution

  • You could keep the reference to the ImageViews in a List.

    List<ImageView> imageViews = new ArrayList<>();
    ...
    Image pic1 = new Image(getClass().getResourceAsStream("/pic1.png"));
    ImageView picView1 = new ImageView(pic1);
    picView1.setFitHeight(PIC_SIZE);
    picView1.setPreserveRatio(true);
    picView1.setSmooth(true);
    imageViews.add(picView1);
    
    Image pic2 = new Image(getClass().getResourceAsStream("/pic2.png"));
    ImageView picView2 = new ImageView(pic2);
    imageViews.add(picView2);
    
    ...
    

    When you need to change the size of the images you can just iterate through the list and set the fitHeight property to the value you want.

    for (ImageView imageView : imageViews) {
        imageView.setFitHeight(PIC_SIZE);
    }