How do I get and display an image in Applet?

To display an image in an applet we first need to obtain the image object itself. A call to applet’s getImage(URL url, String name) method help us to create an image object from the specified URL of the image.

For displaying the image on the applet’s screen we draw it in the paint() method using Graphics.drawImage() method.

package org.kodejava.applet;

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

public class AppletGetImage extends Applet {
    private Image logo;

    @Override
    public void init() {
        // Get an Image object that can be painted on the Applet
        // screen. We need to supply the URL of the document as
        // the base location of the image and the location of the
        // image relative the base URL. 
        logo = getImage(getDocumentBase(), "/images/logo.png");
    }

    @Override
    public void paint(Graphics g) {
        g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
        g.drawImage(logo, 10, 10, this);
    }
}