Question

I have a Image Icon in my Jframe.I am using a Image in it.When i export into a Runnable Jar.The Image is Not displayed.

String iPath = "res/images/Mobile.png";
JLayeredPane layeredPane = new JLayeredPane();
 layeredPane.setBounds(0, 0, 315, 610);
 InputStream stream = (InputStream) getClass().getResourceAsStream(iPath);
 JLabel mobileImageLabel;
 mobileImageLabel = new JLabel(new ImageIcon(iPath));

          //mobileImageLabel = new JLabel(new ImageIcon(ImageIO.read(stream)));
       // mobileImageLabel = new JLabel(new ImageIcon(AppFrame.class.getResource(iPath)));

                    mobileImageLabel.setBounds(0, 0, 315, 610);
                    mobileImageLabel.setVisible(true);
                    layeredPane.add(mobileImageLabel, Integer.valueOf(0));

I googled & found the getResourceAsStream method.But it seems to throw NullPointerException.

So Help me in the Right Direction :)

Thanks for your Help ...

Note The Method i Tried has been Commented

Was it helpful?

Solution

To set a image in a button I did this:

JButton yourButton = new JButton("text button");
        try {
            yourButton.setIcon(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/icon-for-your-button.png"))));
        } catch (IOException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }

You must have the images inside your project like this:

enter image description here

In your case, the answer I think is to do this:

new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/icon-for-your-button.png")))

OTHER TIPS

Try to replace

String iPath = "res/images/Mobile.png";

By

String iPath = "C:/..../res/images/Mobile.png";

Whenever you are working with images try to put the complete path for the image. So when you will generate your .jar file and try to run it from different place(may be possible that you want the jar should be run from desktop) you will get all the images.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top