-2

So I've written a program that compiles, but it won't do what I want it do. It supposed to fill a triangle without using fill polygon. I'm trying to keep the code restricted to loops.

The point is to make the three lines smaller and smaller to fill every part of the triangle. The way to solve this is, I think would be to figure out where the loop should stop. I took a guess at half the height of the triangle (140).

import javax.swing.*;
import java.awt.*;

public class Tri extends JApplet
  {

      int x1=0;
      int y1 = 140;
      int x2 = 120;
      int y2 = 140;
      int x3 = 60;
      int y3;


               public void paint (Graphics page)
               {
                  for (y3= 0; y3<=70; y3++)   
                  {
                  page.drawLine (x1, y1, x2, y2); 
                  page.drawLine (x2, y2, x3, y3);
                  page.drawLine (x3, y3, x1, y1); 


                  y1++;
                  x2--;
                  y2--;
                  x1++;
                  }


               }

   }
munchschair
  • 1,593
  • 3
  • 19
  • 43
  • 1) Please don't forget to add a '?' to questions! Some people do a search in the page for '?' and if none exists in the 'question' go directly to the next (actual) question in line. 2) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). – Andrew Thompson Dec 13 '13 at 18:01
  • This is the not the way to fill a shape. Implement a ***[flood fill algorithm](http://en.wikipedia.org/wiki/Flood_fill)*** – Extreme Coders Dec 13 '13 at 18:07
  • Don't invoke repaint() in a painting method. This will cause in infinite loop. – camickr Dec 13 '13 at 18:08

1 Answers1

1

change your loop logic, try the following code

int x1=0;
  int y1 = 140;
  int x2 = 120;
  int y2 = 140;
  int x3 = 60;
  int y3=0;


           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= 0; x1<=120; x1++)     

           {

              page.drawLine (x3, y3, x1, y1);


           }   }

keep two lines constant and alter the position of other line by changing its coordinates

for information regarding paint() and repaint follow the link

paint() and repaint() in Java `

Community
  • 1
  • 1
wudpecker
  • 386
  • 6
  • 15