0

Working in Java Swing I would like to be able to dynamically change the icon of the JFrame as events happen in the code without having any .pngs. Is there any way to draw the image internally and have it then used as the icon, so that I can do something like the below?

public void Icon(Graphics g){
    ImageIcon img = g.getImageIcon();
    myFrame.setIconImage(img.getImage());
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 2
    You would generate all the `BufferedImage` icons before you create the GUI. Then, during the events, you can change the `JFrame` icon. – Gilbert Le Blanc Apr 17 '22 at 19:30
  • 1
    Further to what @GilbertLeBlanc suggests, the icons used in [this example](https://stackoverflow.com/q/18224184/418556) are all generated at run-time. – Andrew Thompson Apr 17 '22 at 22:36
  • 1
    You can implement the `Icon` interface, for [example](https://stackoverflow.com/a/3072979/230513). – trashgod Apr 17 '22 at 23:25
  • 1
    *"I was able to find a way to code this"* Actually if you took the guru hint from the thread I linked to (many different icon sizes might be used) along with the tip from @trashgod re implementing your own `Icon`, this would result in the most optimal solution. Many icons can be created (all different sizes) and set to the frame as a list. Only the used ones will be rendered, and won't suffer the vagaries of which resizing algorithm the JRE uses. – Andrew Thompson Apr 18 '22 at 02:39

1 Answers1

0

Thanks to input from Gilbert Le Blanc, Andrew Thompson I was able to find a way to code this by using buffed image and Graphics2D

public void Icon(){
   BufferedImage icon = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
   Graphics2D g = icon.createGraphics();
   generateImage(g);
   myFrame.setIconImage(icon);
}

Where generateImage is some function or another to paint the graphics onto g.