The goal is to tesselate a plane using either equilateral triangles, squares, or hexagons, determined by an integer read from a file. The side length is also given by reading an integer from a file. I've done it for squares, but the triangle has me stumped. I've been trying to use drawPolygon
. I assume the side length will correlate to the distance from point a to point b to point c, but i really have no clue as to how to find the coordinates.
import java.awt.*;
import javax.swing.JPanel;
public class DrawShapes extends JPanel {
private int shape; //user choice of which shape to draw
private int sideLength; //user choice of what length to draw the sides
public DrawShapes(int shapeChoice, int sideChoice) {
shape = shapeChoice;
sideLength = sideChoice;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
switch(shape) {
case 3: //Draws triangles
//int[] x =
//int[] y =
//int[] n =
g.setColor(Color.green);
//g.drawPolygon(x,y,n);
break;
case 4: //Draws squares
g.setColor(Color.blue);
g.drawRect(sideLength*i, sideLength*j, sideLength, sideLength);
break;
case 6: //Draws hexagons
break;
}
}
}
}
}
This sounds like a math question. Assuming you are using equilateral triangles, the height of an equilateral triangle is equal to sqrt(3) * base
. Also, to make equilateral triangles tesselate, they alternate up/down, etc.
So if the side length is sidelength
, and the first coordinate is (0,0)
, to draw the first triangle, do:
g.drawLine(0, 0, sidelength, 0); // the top
g.drawLine(0, 0, sidelength/2, sidelength/2 * sqrt(3)); // left side
g.drawLine(sidelength, 0, sidelength/2, sidelength/2 * sqrt(3)); // right side
To draw the upside down triangle, you only need to draw two more sides:
g.drawLine(sidelength, sidelength/2 * sqrt(3), 3 * sidelength/2, sidelength/2 * sqrt(3));
g.drawLine(sidelength, 0, 3 * sidelength/2, sidelength/2 * sqrt(3));
HOWEVER, this is not the best way to do it (draw each triangle by hand). It's better to just draw big lines as the lines are all attached to each other.
private static final double srqtThree = sqrt(3)/2d;
private Dimension d = new Dimension();
private int rootThree;
public DrawShapes(int sideLength) {
rootThree = (int) sideLength * sqrt(3)/2d;
}
public void paintComponent(Graphics g){
getSize(d);
int y = 0;
while(y < d.height) {
// Draw the horizontal line
g.drawLine(0, y, d.width, y);
y = y + rootThree;
}
// Figure this out mostly yourself, but now you draw the angled sides.
// Use this to get started. This is the down-to-right line
g.drawLine(0, 0, d.width / sqrtThree, d.height);
g.drawLine(sideLength, 0, sideLength + (d.width / sqrtThree), d.height);-
// Now draw the down-to-left line
}
Note: you may have to do a lot of size bounds checking to get this to work correctly. But it would be faster than drawing each triangle by hand.