title: Java icon constants - Are static constants ok?
body: <p>I have a number of icons used throughout an application - let's take ok/cancel icons as an example. At the moment they might be a tick and a cross (tick.png, cross.png) but I may want to replace them in future. Also, I would like to keep the resource path in one place.</p>
  
  <p>Is this ok:</p>
  
  <pre><code>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");
  }
  </code></pre>
  
  <p>Or should I be doing this a different way? I don't mind relying on the existence of the image files at runtime since they're in the .jar</p>
  
  <p><strong>Solution</strong></p>
  
  <p>I've used Bent's idea for initialisation, and I've made the constants final:</p>
  
  <pre><code>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);
      }
  }
  </code></pre>