Java Applet Example

Here's an example of a simple Java applet program:

java
import java.awt.*; 
import java.applet.*; 
public class MyApplet extends Applet 
{ public void paint(Graphics g) 
{
 g.drawString("Hello, world!", 20, 20); } 
}

This program creates a basic applet that displays the text "Hello, world!" on a white background. Here's an explanation of the code:

  • The import java.awt.*; line imports the java.awt package, which contains the classes for creating user interfaces.
  • The import java.applet.*; line imports the java.applet package, which contains the classes for creating applets.
  • The public class MyApplet extends Applet line declares a new class called MyApplet that extends the Applet class. This means that MyApplet is an applet.
  • The public void paint(Graphics g) method is called automatically when the applet is created. It takes a Graphics object as a parameter, which is used to draw on the applet's surface.
  • The g.drawString("Hello, world!", 20, 20) line draws the text "Hello, world!" at the point (20, 20) on the applet's surface.

To run this applet, you'll need to create an HTML file that embeds the applet. Here's an example:

php
<html> <head> <title>My Applet</title> </head> <body> <applet code="MyApplet.class" width="200" height="200"></applet> </body> </html>

This HTML file specifies the applet's code (MyApplet.class), as well as its dimensions (width="200" height="200"). When you open this HTML file in a web browser, the applet should appear and display the text "Hello, world!".

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java