在Java中设置图标图像 [英] Set Icon Image in Java

查看:123
本文介绍了在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);

这篇关于在Java中设置图标图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆