This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 9, 2023

What is an applet? How an image can be loaded in applet? Give example.

 An applet is a small Java program that runs within a web browser or applet viewer. It is designed to be embedded within a web page and can be used to add interactive features to a website. Applets are typically used for simple animations, games, and other interactive content.

To load an image in an applet, you can use the getImage() method of the java.awt.Toolkit class. This method returns an Image object, which can then be drawn on the applet using the drawImage() method of the java.awt.Graphics class.

Here is an example of an applet that loads and displays an image:

import java.applet.*;
import java.awt.*;
public class ImageApplet extends Applet {
   Image img;
   public void init() {
      img = getImage(getDocumentBase(), "image.jpg");
   }
   public void paint(Graphics g) {
      g.drawImage(img, 0, 0, this);
   }
}

In this example, we define an applet called ImageApplet that loads an image named image.jpg. The init() method is called when the applet is first loaded, and it uses the getImage() method to load the image from the same directory as the HTML file that embeds the applet. The paint() method is called each time the applet is redrawn, and it uses the drawImage() method to draw the image on the applet's canvas.

To embed this applet in an HTML page, you can use the following code:

<applet code="ImageApplet.class" width="300" height="200">
</applet>

This code specifies the class file for the applet (ImageApplet.class), as well as the width and height of the applet's canvas. When the HTML page is loaded in a web browser, the applet will be displayed and the init() and paint() methods will be called to load and display the image.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget