2

目標は、ファイルから読み取った整数によって決定される、正三角形、正方形、または六角形のいずれかを使用して平面をモザイク化することです。辺の長さも、ファイルから整数を読み取ることによって得られます。私は正方形のためにそれをしましたが、三角形は私を困惑させました. 使ってみましたdrawPolygon。辺の長さは、点aから点b、点cまでの距離に相関すると思いますが、座標を見つける方法については本当に手がかりがありません.

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;
                }
            }
        }
    }
}
4

3 に答える 3

0

10を一辺とし、中心を原点とする直立正三角形を作成します(50, 50)

g.fillPolygon(createTriange(50, 50, 10, false));
private Polygon createPolygon(float x, float y, float side, boolean invert) {
    float xOff = side / 2f;
    float yOff = (float) (xOff * Math.sqrt(3));

    float r1 = 1f / 3f;
    float r2 = 2f / 3f;

    if (invert) { yOff *= -1; }

    Point2D.Float top   = new Point2D.Float(x,        y - (yOff * r2));
    Point2D.Float left  = new Point2D.Float(x - xOff, y + (yOff * r1));
    Point2D.Float right = new Point2D.Float(x + xOff, y + (yOff * r1));

    int xCoords[] = { (int) top.x, (int) left.x, (int) right.x, (int) top.x };
    int yCoords[] = { (int) top.y, (int) left.y, (int) right.y, (int) top.y };

    return new Polygon(xCoords, yCoords, xCoords.length);
}
于 2016-02-10T12:04:08.930 に答える