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

}

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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值