Slip No 6 Q A

Write a java program to blink image on the Frame continuously.

Answer  

package Multithread;
import java.awt.; import java.awt.event.;
public class BlinkImage extends Frame implements Runnable {

Image img;
Thread t;
boolean show = true;

public BlinkImage() {
    img = Toolkit.getDefaultToolkit().getImage("4-cs.jpg"); // put image in project folder

    setTitle("Blinking Image");
    setSize(400, 300);
    setVisible(true);

    t = new Thread(this);
    t.start();

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

public void run() {
    try {
        while (true) {
            show = !show;   // toggle visibility
            repaint();
            Thread.sleep(100); // blinking speed
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void paint(Graphics g) {
    if (show) {
        g.drawImage(img, 100, 80, 150, 100, this);
    }
}

public static void main(String[] args) {
    new BlinkImage();
}
}

Spread the love

Leave a Comment

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

Scroll to Top