1

I checked many previous questions here on stackoverflow but none has been a solution to the problem I have. I must "simply" insert an icon in my JFrame, I tried to do it this way (from another stackoverflow question):

// ico file is in the same folder
ImageIcon frameIcon = new ImageIcon("/iconqm16.ico");
jFrame1.setIconImage(frameIcon.getImage());

but this didn't work. After this I tried the following:

URL iconURL = getClass().getResource("/iconqm(20x20).png");
ImageIcon icon = new ImageIcon(iconURL);
jFrame1.setIconImage(icon.getImage());

This time I used .png because I read that .ico is Windows specific. And I used class resource because it can be packed in the jar. But my icon doesn't appear yet. Someone can find any error in these snippets? Maybe it is a problem of image dimensions? I tried 16x16, 20x20, 32x32 but none worked.

EDIT

I found out the problem. Tried this code below and my program can't find the file even if the path is correct. I checked it well before editing my question, can you help me understand why can't find the image file?

URL url = getClass().getResource("C:/Users/Sergio/Documents/NetBeansProjects/Queue Manager v1.0/icon/icon16px.png");
    if (url == null) {
        System.out.println("Could not find image!");
    } else {
        jFrame1.setIconImage(new ImageIcon(url).getImage());
    }
}

EDIT This finally worked, but honestly I don't get the reason why getClass().getResource(pathToFile) did not work. Used this solution:

try {
    // Set Frame's Icon
    BufferedImage img = ImageIO.read(new File("C:\\Users\\Sergio\\Documents\\NetBeansProjects\\Queue Manager v1.0\\icon\\icon16px.png"));
    this.setIconImage(img);
} catch (IOException ex) {
    Logger.getLogger(QueueManagerForm.class.getName()).log(Level.SEVERE, null, ex);
}

Thanks for the help!

Sergio
  • 31
  • 9
  • Use ImageIO to read the image file. If it can't read the image you will get an error message. – camickr Dec 03 '19 at 15:23
  • Can you make or redirect me to an example of how to use it to set the frame icon? – Sergio Dec 03 '19 at 18:07
  • 1
    There is no trick. You use `ImageIO.read(...)` to read the `Image`, then you use the `setIconImage(...)` method. If you have never used ImageIO before then read the API or search the forum for examples. If you need more help post a proper [mre] demonstrating the problem. Note I have used 16x16 and 64x64 gif files and have not had any problems. I suggest you also read [How to Use Icons](https://docs.oracle.com/javase/tutorial/uiswing/components/icon.html). Maybe you have your class path is wrong. Are you able to display the Icon a JLabel? – camickr Dec 03 '19 at 18:25

0 Answers0