Search code examples
javaapplet

Image is not displaying on applet


This is the code I used for displaying an image in applet.The applet is working, but not displaying the image.The image is present in the src folder.

import java.awt.*;  
import java.applet.*;  


public class DisplayImage extends Applet {  

Image picture;  

public void init() {  
 picture = getImage(getDocumentBase(),"IMG-20160319-WA0003.jpg");  
}  

public void paint(Graphics g) {  
 g.drawImage(picture, 30,30, this);  
}  

} 

The HTML code:

     <html> 
       <HEAD>
   </HEAD>
<body>  
<applet code="DisplayImage.class" width="300" height="300">  
</applet>  
</body>  
</html>  

Solution

  • Make sure that the image is in the same folder as the .class file, and not the .java file, as the .class file is the one that is being executed.

    A better solution still would be to create a jar containing the code and the image. The base folder of the jar I created looks as follows:

    enter image description here

    Within the applet folder you can find the .class files. Put the jar file in the same folder as you html file. You then have to adapt your .html file:

    <!DOCTYPE html>
    <html>
        <head>
        </head>
        <body>
            <applet archive="applet.jar" code="applet.DisplayImage.class" width="300" height="300">  
            </applet> 
        </body>
    </html>