How to set Icon to JFrame

90,668

Solution 1

Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).

URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());

Though you might even think of using setIconImages for the icon in several sizes.

Solution 2

Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.

    this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());

1) Put this code in jframe WindowOpened event

2) Put Image in main folder where all of your form and java files are created e.g.

src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png

3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.

this way your icon will be there even after finally building your project.

Solution 3

This works for me.

    frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));

For the export jar file, you need to configure the build path to include the res folder and use the following codes.

    URL url = Main.class.getResource("/icon.png");
    frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));

Solution 4

Yon can try following way,

myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));

Solution 5

Here is the code I use to set the Icon of a JFrame

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

  try{ 
    setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
  } 
  catch (IOException e){
    e.printStackTrace();
  }
Share:
90,668
vijay
Author by

vijay

Working as an intern on a Java project with the knowledge of java and java GUI

Updated on February 11, 2020

Comments

  • vijay
    vijay over 4 years

    I tried this way, but it didnt changed?

    ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
    frame.setIconImage(icon.getImage());