0
Rotating Colorful Squares
Definition:
Write an applet that draws four squares of equal size & of different colors such that they cover up the whole applet area. The applet should operate correctly even if it is resized.
import java.applet.*;
import java.awt.*;
public class rotateSquares extends Applet implements Runnable
{
Color[] clr = {Color.red, Color.green, Color.pink, Color.blue};
int cnt = 0;
Thread t;
public void init()
{
t = new Thread(this);
t.start();
setBackground(Color.black);
}
public void run()
{
try
{
while(true)
{
repaint();
t.sleep(1000);
cnt++;
if(cnt>3){cnt=0;}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public void paint(Graphics g)
{
int w = getWidth();
int h = getHeight();
int tmp = cnt;
for(int i=0;i<4;i++)
{
g.setColor(clr[tmp++]);
if(tmp>3)tmp=0;
if(i==0) g.fillRect(0,0,w/2,h/2);
else if(i==1) g.fillRect(w/2,0,w/2,h/2);
else if(i==2) g.fillRect(w/2,h/2,w/2,h/2);
else if(i==3) g.fillRect(0,h/2,w/2,h/2);
}
}
}
/*
<applet code="rotateSquares" width="500" height="500"></applet>
*/
Output:




Recent Comments