3

我正在使用一种createAndShowGUI()方法来创建一个JFrame. 我正在尝试设置一个图标,但是当我在 NetBeans 中运行它时,它没有显示。但是,当我运行一个.jar文件(图像在同一个文件夹中)时,它可以正常工作。

private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame game = new JFrame();
    game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.setSize(198, 409);  
    game.setResizable(false);
    game.setTitle("Frame Title"); 
    ImageIcon img = new ImageIcon("Icon.png");
    game.setIconImage(img.getImage());
    game.setVisible(true);

}

问题可能出在哪里?

4

2 回答 2

4

你为什么不制作这样的包:

org.icon 

并将图标添加到该包。

要设置图标,请使用:

ImageIcon img = new ImageIcon(Game.class.getResource("/org/Icon/NameOfIcon.png"));
game.setIconImage(img.getImage());

您的程序将没有问题找到一个图标。

于 2012-11-06T21:19:54.913 回答
3

当我使用测试图像运行上述代码时,图标已正确更改。添加:

System.out.println(System.getProperty("user.dir"));

到方法以显示图像位于的文件夹并在必要时将其复制到那里。

于 2012-11-06T20:27:02.270 回答