Java - Applet - Hello World Example

  1. Create a new Java project in your IDE.
  2. Create a new package inside the project for your applet.
  3. Create a new Java class and name it something like "MyApplet".
  4. Have the class extend the JApplet class.
  5. Override the init() method of the JApplet class to initialize your applet.
  6. Override the paint() method of the JApplet class to draw on your applet.
  7. Compile your applet class.
  8. Create an HTML file with the necessary code to embed your applet.
  9. Open the HTML file in a web browser to view your applet.

Here's an example code that you can use to create a simple Java applet that displays "Hello, world!" in the center of the applet:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;

public class MyApplet extends JApplet {

    @Override
    public void init() {
        setBackground(Color.WHITE);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.BLACK);
        g.drawString("Hello, world!", getWidth() / 2 - 30, getHeight() / 2);
    }
}

In this example, we created a new Java class called "MyApplet" that extends the JApplet class. We then overrode the init() method to set the background color of the applet to white. Finally, we overrode the paint() method to draw the string "Hello, world!" in black at the center of the applet.

To compile this code, you would need to run the following command:

javac MyApplet.java

Once compiled, you can create an HTML file with the following code to embed your applet:

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

This HTML code creates a new applet element and sets the code attribute to the name of the compiled class file (MyApplet.class). It also sets the width and height attributes to 200 pixels.

Save this HTML file with a name like "myapplet.html" and open it in a web browser to view your applet. You should see a white background with the text "Hello, world!" in black at the center of the applet.