在Java中设置图标图像

问题描述:

我一直在搜索如何在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);

}

我的图片路径是%PROJECT%/ res /Image.png我只是使用/Image.png继续访问我的res文件夹(正如我在项目的其他部分所做的那样)我甚至将它转换为图标文件,然后尝试了,但所有这一切决定是使用默认的Java图标。

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.

您的问题通常是由于查找图像的错误位置,或者如果您的类和图像位于jar文件中,则查找文件不存在的文件。我建议您使用资源摆脱第二个问题。

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.

例如,

// 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);