Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Icon Image in Java

I have been searching everywhere on how to set the icon image in Java, and it always ends up not working or it gives me errors. Here, in my main method is where I put the code:

public static void main(String[] args) {
    Game game = new Game();

    // This right here! 
    game.frame.setIconImage(new ImageIcon("/Icon.png").getImage());

    game.frame.setResizable(false);
    game.frame.setTitle(title);
    game.frame.add(game);
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.frame.setLocationRelativeTo(null);
    game.frame.setVisible(true);

}

My path for the image is "%PROJECT%/res/Image.png" and I just use /Image.png to go ahead and access my res folder (as I have done in other parts of my project) I have even converted it into an icon file, and tried that, but all it decides is to use the default Java icon.

like image 383
Shzylo Avatar asked Jun 29 '13 19:06

Shzylo


3 Answers

Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.

e.g.,

// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);

// use icon here
game.frame.setIconImage(myImg);
like image 75
Hovercraft Full Of Eels Avatar answered Oct 13 '22 01:10

Hovercraft Full Of Eels


Use Default toolkit for this

frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
like image 26
Jayram Avatar answered Oct 13 '22 01:10

Jayram


I use this:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class IconImageUtilities
{
    public static void setIconImage(Window window)
    {
        try
        {
            InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
            BufferedImage bufferedImage = ImageIO.read(imageInputStream);
            window.setIconImage(bufferedImage);
        } catch (IOException exception)
        {
            exception.printStackTrace();
        }
    }
}

Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:

IconImageUtilities.setIconImage(this);
like image 37
BullyWiiPlaza Avatar answered Oct 13 '22 00:10

BullyWiiPlaza