Tower's Vault
Tower's Vault

Reputation: 61

Issues with setIconImage()

So I am still quite a newbie when it comes to creating JFrame apps. I have decided to learn a bit more about it by creating a hobby of a project, all has been going pretty well, and I have learnt a lot, but now I'm trying to learn how to use setIconImage() for, ya know, the icon in the top left hand corner of the window (in Windows, not sure in which corner it is shown on Mac OSX and Linux). I have Googled far and wide, however could not really find anything that worked 100%, either it worked in Eclipse, or I got NullPointerExceptions. From what I understand is that when running the .jar file from your desktop, it would do a search for the icon image by starting at your PC's root directory, and not the .jar's root directory. Anyone got some tips on this that might help? I have pasted my source code for the class that handles the main method for me below, the other classes deal with creating the JFrame, and in this case do the password generation (this is part of the tiny password generator app I made for my office)

Source Code:

    public class ShowWindowDemo()
    {
        private static final String ICON_PATH = "src\\images\\p_gen.png";

        public static void main(String[] args)
        {
            WindowDemo() gui = new WindowDemo();
            gui.setVisible(true);
            gui.setResizable(false);
            gui.setIconImage(Toolkit.getDefaultToolkit().getImage(
                ShowWindowDemo.class.getResource(ICON_PATH)));
            gui.setLocationRelativeTo(null);
            gui.setTitle("PassGen v1.0.6");
        }
    }

My folder structure for getting to the .png images is src/images/. Whenever I try to run my app in Eclipse using the above mentioned source code, it opens fine, but in my console I get a NullPointerException. I have run the app by using

    gui.setIconImage(Toolkit.getDefaultToolkit().getImage(ICON_PATH));

and it works 100% fine.

Any assistance on this would be GREATLY appreciated, I am a bit stuck on this one it seems.

Upvotes: 0

Views: 563

Answers (2)

Javasamurai
Javasamurai

Reputation: 686

Try create a folder named "Images" in your project and copy all the images in that folder.Then test this code:

gui.setIconImage(new ImageIcon(getClass().getResources("Images/image_name.png"),"An image"));

Hope that helps.

Upvotes: 0

redMist
redMist

Reputation: 229

Try using /images/p_gen.png as ICON_PATH. I am getting my icon image like this (i am using javafx, but it should be similar) :

primaryStage.getIcons().add(new Image("/images/four85.png"));

Upvotes: 1

Related Questions