Cyril Bremaud
Cyril Bremaud

Reputation: 117

Reduce code for lazy loading image

I have a lot of images to load and I want the loading to be lazy. At this point I wrote a class with all my loaded images.

public static ImageIcon binIcon = getBinIcon();
private static ImageIcon getBinIcon() {
    if(binIcon == null) {
        return binIcon = FileManipulation.getImage("img/bin.jpg");
    }
    else {
        return binIcon;
    }
}

public static ImageIcon checkboxIcon = getCheckboxIcon();
private static ImageIcon getCheckboxIcon() {
    if(checkboxIcon == null) {
        return checkboxIcon = FileManipulation.getImage("img/checkbox.png");
    }
    else {
        return checkboxIcon;
    }
}

...

Finally I have a lot of duplicate code, I'm looking for a sexy way to reduce it.

Thank you for your ideas !

Upvotes: 0

Views: 104

Answers (2)

Guillaume Barré
Guillaume Barré

Reputation: 4218

You can create a method receiving the icon to load and the file name :

public static ImageIcon checkboxIcon;
public static ImageIcon binIcon;

private static ImageIcon getCheckboxIcon(ImageIcon icon, String fileName) {
    return icon == null ? FileManipulation.getImage(fileName) : icon;
}

It will allow you to load the icons this way :

binIcon = getCheckboxIcon(binIcon, "img/bin.png");
checkboxIcon = getCheckboxIcon(checkboxIcon, "img/checkbox.png");

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

Object oriented simply - a class LazyImageIcon extends ImageIcon. Then you could even postpone the reading to the first painting, if given right image size to the constructor.

Upvotes: 1

Related Questions