Java Icon Constants - Are Stationary Constants OK?

I have many icons used throughout the application - let ok / cancel as an example. At the moment, they can be a tick and a cross (tick.png, cross.png), but I may want to replace them in the future. In addition, I would like to save the resource path in one place.

This is normal:

public class Icons {
    public static Icon OK = new ImageIcon(Icons.class.getResource("/icons/tick.png");
    public static Icon CANCEL = new ImageIcon(Icons.class.getResource("/icons/cross.png");
}

Or should I do it differently? I don't mind relying on the existence of image files at runtime, since they are in .jar

Decision

I used the Bent idea to initialize, and I made the constants final:

public final class Icons {
    private static final Logger logger = Logger.getLogger(Icons.class);

    public static final Icon OK = icon("/icons/add.png");
    public static final Icon CANCEL = icon("/icons/cancel.png");

    private static Icon icon(String path) {
        URL resource = Icons.class.getResource(path);
        if(resource==null) {
            logger.error("Resource "+path+" does not exist");
            return new ImageIcon();
        }
        return new ImageIcon(resource);
    }
}
+5
source share
5 answers

, ImageIcon ;

public static final Icon ok = icon("ok.png");


private static Icon icon(String path) {

    URL resource = Icons.class.getResource("/icons/" + path);
    if (resource == null) {
        // Log something...
        return null;
    }
    return new ImageIcon(resource);
}

, , - , .

, .

Icons Icon . , , . , .

+1

, :

  • , . , , , "" .
  • , , , , , .

1, , , , .

2, , , , , .

, , , .

+3

final.

+2

, . , ( "ok.png", "cancel.png" ). , , .

0

, , -, .

Eclipse Maven maven, Eclipse , /. , .

maven , .

0

All Articles