How to Draw a Car using Java Applet?

An Applet is a Java program that runs in a web browser. An Applet is a Java class that extends the java.applet.Applet class, which means that to create any Applet, you need to import this class and extend it in your Applet class. The applet does not have a main() method. Applets are designed to embed in an HTML page. A JVM is needed to view the applet.

Drawing a car using a Java applet involves using the Graphics class to create various shapes representing different car parts. Below is an example of how we can achieve this by extending the Applet class and overriding the paint method to draw the car.

Prerequisite:

Java Version: Applet features are not available above Java 8. To run this code, Java 8 or an earlier version such as Java 7 or Java 6 is required.

Steps to Create and Run a Car Drawing Applet

Step 1: Write the Java Code

Create a Java file named Car.java with the following content:

Java
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.lang.*;

public class Car extends Applet {
    public void paint(Graphics g) {
        // Draw car body
        g.setColor(Color.RED);
        g.fillRect(50, 100, 200, 50);
        g.fillRect(75, 75, 150, 50);

        // Draw windows
        g.setColor(Color.CYAN);
        g.fillRect(110, 80, 30, 30);
        g.fillRect(160, 80, 30, 30);

        // Draw wheels
        g.setColor(Color.BLACK);
        g.fillOval(75, 140, 50, 50);
        g.fillOval(175, 140, 50, 50);

    }
}


Step 2: Create the HTML File

Create an HTML file named index.html with the following content:

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Simple Car Applet</title>
</head>
<body>
    <applet code="Car.class" width="300" height="200">
        Your browser does not support Java applets.
    </applet>
</body>
</html>


Step 3: Compile the Java Code

Open a command prompt or terminal and navigate to the directory where Car.java is located. Compile the Java file using the below command:

javac <file name>.java

Step 4: Run the Applet

Now, use the appletviewer command to run the applet. Ensure the index.html file is in the same directory as Car.java and its compiled class file. Execute the below command:

appletviewer <html file name>.html

This will open a new window and display the output.

Output:

Note:

  • Ensure that the Car.class file is in the same directory as the HTML file.
  • Open the HTML file in a browser that supports Java applets (Modern browsers have largely deprecated support for Java applets. You might need to use older versions or specific browsers that still support applets, or an applet viewer).




    Contact Us