Shz*_*ylo 9 java icons swing image
我一直在搜索如何在Java中设置图标图像,它总是不起作用或它给我错误.在这里,我的主要方法是我把代码放在哪里:
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);
}
Run Code Online (Sandbox Code Playgroud)
我的图像路径是"%PROJECT%/ res/Image.png",我只是使用/Image.png继续访问我的res文件夹(正如我在项目的其他部分所做的那样)我甚至已将其转换为进入一个图标文件,并尝试了,但它决定使用默认的Java图标.
您的问题通常是由于查找图像的错误位置,或者您的类和图像位于jar文件中,然后查找文件不存在的文件.我建议您使用资源来摆脱第二个问题.
例如,
// 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);
Run Code Online (Sandbox Code Playgroud)
使用默认工具包
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92708 次 |
| 最近记录: |