Search code examples
javaloopsgeometryfill

How to fill a triangle using lines from a loop


I can't figure out the logic behind this.I drew a triangle in Java, but now I'm trying to fill that triangle with lines from a For Loop.

Can someone tell me what I'm doing wrong?

import java.awt.Graphics;

import javax.swing.JApplet;

public class Triangle extends JApplet {

int x1 = 300;
int x2 = 206;
int y2 = 206;
int y1 = 71;
int y3 = 206;
int x3 = 400;

public void paint(Graphics page) {
    page.drawLine (x1,y1,x2,y2);
    page.drawLine(x2, y2, x3, y3);
    page.drawLine(x3, y3, x1, y1);


    for (x1 = 300; x1<= 506 ; x1++){
        page.drawLine(x3, y3, x1, y1);


    }


}

}


Solution

  • You should use page.fillPoly()

    int[] xPoints = {x1, x2, x3};
    int[] yPoints = {y1, y2, y3};
    page.fillPoly(xPoints, yPoints, 3);
    

    See Graphics#fillPoly()

    Edit: Try something like this, for an upside-down half-pyramid

    int x1 = 0;
    int y1 = 0;
    int x2 = 100;
    int y2 = 0;
    
    for (int i = 0; i < x2; i++){
        g.drawLine(x1, y1, x2, y2);
        x1 += 1;
        y1 += 1;
        y2 += 1;
    }
    

    This hasn't been tested, but I'm assuming at should print something like this

    --------------
     -------------
      ------------  // with no spaces of course.
       -----------
        ----------
         ---------
          --------
     .. and so on
    

    Again this is just a guess.


    Edit: Tested and Approved :)

    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Test extends JPanel {
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
    
            int x1 = 0;
            int y1 = 0;
            int x2 = 100;
            int y2 = 0;
    
            for (int i = 0; i < x2; i++) {
                g.drawLine(x1, y1, x2, y2);
                x1 += 1;
                y1 += 1;
                y2 += 1;
            }
        }
    
        public Dimension getPreferredSize() {
            return new Dimension(100, 100);
        }
    
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.add(new Test());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        }
    }
    

    Result

    enter image description here