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!