0

What is the fastest way of accessing an image file (.png) that is in the project and setting it as the icon of something?

randers
  • 5,031
  • 5
  • 37
  • 64
  • Is there a particular reason why you are asking? Are you having performance issues with loading images or are you simply curious? – randers Feb 21 '16 at 19:17
  • I just wanted to change icon of a button everytime it is clicked, and by doing this, i think i must setIcon to the image file that i get – iamkentleom Feb 21 '16 at 19:23
  • In that case, why don't you create a instance of every icon you need ahead-of-time? – randers Feb 21 '16 at 20:04
  • `ImageIcon icon1 = ...; ImageIcon icon2 = ...;` and in your action listener you just swap them out. – randers Feb 21 '16 at 20:21
  • But how do you get the image and set it? – iamkentleom Feb 21 '16 at 20:22
  • 2
    What do you mean by "fastest way"? Rendering an image will always take time; loading an image will always take time. You could use some pre-caching and/or make sure the color models are compatible, but that all needs more context, for example, if you're loading 4k images, you might not have enough memory to load many simultanously – MadProgrammer Feb 21 '16 at 22:54

2 Answers2

0

I'm not sure what performance gains you expect from different solutions, since this task is mainly I/O-based. To load a .png from a file and set it as the icon of a button, you can do the following:

File theFile = ...;
button.setIcon(new ImageIcon(theFile.toURI().toURL()));
randers
  • 5,031
  • 5
  • 37
  • 64
  • 2
    [Reading/Loading an Image](http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html) would be a more robust solution as it won't invoke a background thread to load the image and will throw an exception if the file can't be read for some reason – MadProgrammer Feb 21 '16 at 22:52
0

I recently just figure it out and it turns out to be like this button.setIcon(new.javax.swing.ImageIcon(getClass().getResource("/image.png")));