문제

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

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top