Slip No 11 Q B

Q. Write an applet application to display Table lamp. The color of lamp should get change randomly. [25 M]

import java.applet.Applet;
import java.awt.*;
import java.util.Random;

/*
<applet code="TableLamp" width=400 height=400>
</applet>
*/

public class TableLamp extends Applet implements Runnable {

    Color lampColor;
    Random rand = new Random();
    Thread t;

    public void init() {
        t = new Thread(this);
        t.start();
    }

    // Thread to change color randomly
    public void run() {
        while(true) {
            lampColor = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
            repaint();
            try {
                Thread.sleep(1000);   // change color every second
            } catch(Exception e) {}
        }
    }

    public void paint(Graphics g) {

        // Table
        g.setColor(Color.DARK_GRAY);
        g.fillRect(100, 300, 200, 20);

        // Lamp stand
        g.setColor(Color.BLACK);
        g.fillRect(190, 200, 20, 100);

        // Lamp shade (changing color)
        g.setColor(lampColor);
        g.fillArc(150, 120, 100, 80, 0, 180);

        // Bulb
        g.setColor(Color.YELLOW);
        g.fillOval(180, 180, 40, 40);
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top