简体   繁体   中英

Reading and storing Java Icons

In my Java application I'm planning to use a lot of ImageIcon s which will be shown in JLabel s. The size of a single .png file is about 8 kB. During runtime, icons will be shown in JLabel s, but the icons shown in the labels will change often, using .setIcon(icon) .

Should I load all those icons at once when the program starts and store those in an array (length would be > 150) or should I load the icons every time I change an Icon as shown in the code below?

Note that the number of JLabel s is rather small, so, at a given moment, only a selection of icons is shown.

ClassLoader cl = getClass().getClassLoader();
String path = "somePath";
URL url = cl.getResource(path);
Icon icon = new ImageIcon(url);

The application will be a jar file with the resources inside the jar.

This will be a bit cliche, but "Do not optimize your application unless it needs to be optimized." It makes maintenance more difficult in future.

Because, every program evolves in time, and the kind of the optimization required may not be the one you are planning to do at the moment. Your JLabels may increase in number, or your possible icons may increase. Or some other new feature comes up and you may need to display all the icons at the same time etc. etc.

So, just write your code as clean as possible, and when you see that an optimization is really required, do it after measuring where is the bottle neck.

PS: I am telling this, because you write "I am planning to use" so you did not actually finished the application and saw the effect of this many icon loadings.

PS2: OS and Disk caches are getting better everyday, so it may just be enough for the time being.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM