CJ_Slip_11B

Slip No.11

B) Write an applet application to display Table lamp. The color of lamp should get change randomly.

1. Open Notepad.

2. Type the following code:

    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.util.Random;

    public class TableLampApplet extends Applet implements Runnable {

    private Color lampColor;
    private Thread thread;

    @Override
    public void init() {
    lampColor = Color.YELLOW; // Initial color
    thread = new Thread(this);
    thread.start();
    }

    @Override
    public void paint(Graphics g) {
    // Draw the table lamp base
    g.setColor(Color.DARK_GRAY);
    g.fillRect(90, 150, 20, 80); // base

    // Draw the lamp shade with the current lamp color
    g.setColor(lampColor);
    g.fillOval(50, 50, 100, 100); // lamp shade

    // Draw the lamp post
    g.setColor(Color.GRAY);
    g.fillRect(90, 130, 20, 20); // post
    }

    @Override
    public void run() {
    Random rand = new Random();

    while (true) {
    // Generate random color for the lamp
    lampColor = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));

    // Repaint the applet to reflect the new color
    repaint();

    try {
    Thread.sleep(1000); // Change color every 1 second
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
3. Save the file with the name TableLampApplet.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Create an HTML file to run the applet. Save the following code in a file named TableLampApplet.html:
    <html>
    <body>
    <applet code="TableLampApplet.class" width="400" height="200">
    </applet>
    </body>
    </html>
5 Open the Command Prompt.

6 Compile the Java program by typing:
javac TableLampApplet.java

7. Run the applet using an applet viewer or a compatible web browser. You can use the appletviewer tool that comes with the JDK to run the HTML file:
appletviewer TableLampApplet.html

No comments:

Post a Comment