Search code examples
javaswingjframegetresource

How to get resources working in runnable jar?


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


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