I'm very new to Java, and find myself having a bit of trouble looping. I am to first design a simple applet to build a house, for which I have the code below:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Polygon;
public class Houseref extends Applet
{
public void paint (Graphics page)
{
Polygon poly = new Polygon(); // Roof Polygon
poly.addPoint (50,90);
poly.addPoint (150, 50);
poly.addPoint (250, 90);
page.setColor (new Color(218,165,32)); // Custom brown color
page.fillPolygon (poly);
page.setColor (Color.black);
page.drawLine (50, 90, 150, 50); // Roof outline
page.drawLine (150, 50, 250, 90);
page.setColor (Color.yellow);
page.fillRect (50, 90, 200, 100); // House base with houseColor
page.setColor (Color.black);
page.drawRect (50, 90, 200, 100); // House outline
page.setColor (Color.black);
page.fillRect (75, 110, 30, 25); // Window 1
page.fillRect (190, 110, 30, 25); // Window 2
page.setColor (Color.blue);
page.drawLine (75, 123, 105, 123); // Window Frame 1
page.drawLine (89, 110, 89, 134);
page.fillRect (70, 110, 5, 25); // Shutter 1
page.fillRect (105, 110, 5, 25); // Shutter 2
page.drawLine (75+115, 123, 105+115, 123); // Window Frame 2
page.drawLine (89+115, 110, 89+115, 134);
page.fillRect (70+115, 110, 5, 25); // Shutter 3
page.fillRect (105+115, 110, 5, 25); // Shutter 4
page.setColor (Color.blue);
page.fillRect (130, 150, 35, 40); // Door
page.setColor (Color.red);
page.fillOval (155, 170, 4, 4); // Door knob
}
}
Now I need to create a loop that iterates 5 times, each time the new house must be in a different color and in a different location. I'm having trouble with understanding how to get an applet to loop. Any help is appreciated!
You don't loop an applet. You loop within an applet, as arg0's answer illustrates.
You've used magic numbers all through your paint method. You need to change the magic numbers to fields so you can change the variables.
The first thing you need to do is refactor your paint method so that you have lots of little methods. You should have a drawWall method, a drawRoof method, a drawDoor method, and a drawWindow method you call twice.
I'm assuming by different color houses you mean the wall should be different colors. You pass the color to the wall method you create as a parameter.
Here's a refactored drawWall method, so you can see what I'm talking about. You'll need to break up the rest of your paint method this way.
private void drawWall(Graphics page, Color color, int x, int y, int width,
int height) {
page.setColor(color);
page.fillRect(x, y, width, height); // House base with houseColor
page.setColor(Color.black);
page.drawRect(x, y, width, height); // House outline
}
The Rectangle class would be a good way to pass x, y, width, and height values to the method.