The applet draws a row of houses:
import java.awt.*;
import java.applet.Applet;
public class Steet extends Applet
{int size;
public void init ()
{size = 40;
}
public void paint (Graphics g)
{drawHouse (g, 50, 100, size);
drawHouse (g, 100, 100, size);
drawHouse (g, 150, 100, size);
drawHouse (g, 200, 100, size);
drawHouse (g, 250, 100, size);}
private void drawHouse (Graphics g, int xCoord, int yCoord, int size)
{g.drawRect (xCoord, yCoord, size, size);
g.drawLine (xCoord, yCoord, xCoord+size/2, yCoord-size/2);
g.drawLine (xCoord + size/2, yCoord- size/2, xCoord+size, yCoord);}
}
This is the output
Type in this variation and see what happens to the houses:
import java.awt.*;
import java.applet.Applet;
public class Steet extends Applet
{int size;
public void init ()
{size = 80;
}
public void paint (Graphics g)
{drawHouse (g, 50, 100, size);
size = size*4/5;
drawHouse (g, 100, 100, size);
size = size*4/5;
drawHouse (g, 150, 100, size);
size = size*4/5;
drawHouse (g, 200, 100, size);
size = size*4/5;
drawHouse (g, 250, 100, size);}
private void drawHouse (Graphics g, int xCoord, int yCoord, int size)
{g.drawRect (xCoord, yCoord, size, size);
g.drawLine (xCoord, yCoord, xCoord+size/2, yCoord-size/2);
g.drawLine (xCoord + size/2, yCoord- size/2, xCoord+size, yCoord);}
}
Just to illustrate that there is more than one way to skin a cat. Have a look at this example. In the above examples the house is declared as a method and called multiple times. An alternative way to approach this is to work on the Graphics object and effectively call sections of that object a number of times using the copyArea method.
import java.awt.*;
import java.applet.Applet;
public class CopyHouses extends Applet
{public void paint (Graphics g)
{g.setColor(Color.BLUE);
g.fillRect(50,50,50,50);
g.setColor(Color.RED);
g.drawLine(50, 50, 75, 30);
g.drawLine(75,30,100,50);
g.setColor(Color.YELLOW);
g.fillRect(55, 60, 10, 10);
g.fillRect(85, 60, 10, 10);
g.setColor(Color.GREEN);
g.fillRect(68, 80, 15, 20);
for (int cnt=0;cnt<5;cnt++)
{g.copyArea (0,0,100,120,cnt*150,0);
}
}
}