0

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).

Doerad
  • 69
  • 1
  • 7
  • 2
    Why not create a method that accepts a list of Images and styles them all the same way? Or just loop through the list and do it right in your main code. – Zephyr Feb 13 '19 at 19:30
  • `for (int i = 1; i <= 2; i++) { Image pic = new Image(getClass().getResourceAsStream("/pic" + i + ".png")); ... }`??? – fabian Feb 13 '19 at 19:37

2 Answers2

1

I can suggest to group the views in one class with all the needed methods in it. In that way you can easy add new functionalities later, instantiate new groups and manipulate the views in them.

public class ImageViewGroup {

private Map<String, ImageView> imagaViews;

public ImageViewGroup() {
imagaViews = new HashMap<>();
}

public void addNewImageView(String someIdentifierForRetrieval, String imagePath, double size) {
Image image = new Image(getClass().getResourceAsStream(imagePath));
ImageView imageView = new ImageView(image);
imageView.setFitHeight(size);
imageView.setPreserveRatio(true);
imageView.setSmooth(true);

imagaViews.put(someIdentifierForRetrieval, imageView);
}

public void resizeAllImageViews(double newSize) {
for (ImageView imageView : imagaViews.values()) 
    imageView.setFitHeight(newSize);
    }

}

PS: Code not tested.

1

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);
}
crowde
  • 321
  • 1
  • 12