简体   繁体   中英

Java Applet Image Load

I want to display an image icon in my applet.I created a package resources and saved my image in it.This is what i tried :-

Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor

And i use this proceedure

 public Image getImage(String name){
                URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
                ImageIcon icon = new ImageIcon(imgUrl);
                return icon.getImage();
            }

 public void paint(Graphics g)
        {
             if (logo!=null){
                    g.drawImage(logo, 30, 30, null);
                }
             g.drawString("Hwllo", 12, 12);
        }

Then i call the:

repaint() //In the Constructor

But i dont see an image or my String.What might be the problem.Moreover is there any easier method to load images in the Applet??

You setting the URL to the

URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
ImageIcon icon = new ImageIcon(imgUrl);

But while Calling paint method, you are calling the logo variable

 g.drawImage(logo, 30, 30, this);

The problem is in your setting URL value, set URL to your logo variable like

URL url = new URL(/*Your resources herre*/, /*Your file name here*/);
logo=getImage(url);

After that display image using paint method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM