AlecP
AlecP

Reputation: 11

How do I set an icon for my JFrame from the resources?

I am trying to set an icon image for my JFrame program. I can set it from an external location using this code:

JFrame jf = new JFrame("The Stick Hero");
try{
jf.setIconImage(ImageIO.read(new File("C:/sample/imagesample.png");
}catch (Exception e);
e.printStackTrace();

but if I try to do this from a resources file like this (The Images folder is in the resources src I made)

JFrame jf = new JFrame("The Stick Hero");
try{
jf.setIconImage(ImageIO.read(new File("/Images/Icon/png");
}catch (Exception e);
e.printStackTrace();

It doesn't work. It just appears as the java icon. Is there any way I can set it from the resources file?

Upvotes: 1

Views: 966

Answers (1)

gst990wrz
gst990wrz

Reputation: 11

It seems you need to add "/resources/" to your icon path:

JFrame jf = new JFrame("The Stick Hero");
try{
    jf.setIconImage(new ImageIcon(Toolkit.getDefaultToolkit().getClass().getResource("/resources/Images/Icon/imagesample.png")).getImage());
}catch (Exception e);
e.printStackTrace();

Upvotes: 1

Related Questions