How to fill color on triangle
Asked Answered
G

3

8

I draw a triangle using line. How can I fill color on it? So far I can only success color the line but not fill the color.

public void paintComponent(Graphics g){
        super.paintComponents(g);
        int k=0;
        for (j=0 ; j < numOfLines; j++){    // the values of numOfLines retrieved from other method.
        g.setColor(Color.green);
        g.drawLine(x[k], x[k+1], x[k+2], x[k+3]);
        k = k+4;  //index files
        }
Guilt answered 24/3, 2009 at 1:36 Comment(0)
R
20

Make a Polygon from the vertices and fill that instead, by calling fillPolygon(...):

// A simple triangle.
x[0]=100; x[1]=150; x[2]=50;
y[0]=100; y[1]=150; y[2]=150;
n = 3;

Polygon p = new Polygon(x, y, n);  // This polygon represents a triangle with the above
                                   //   vertices.

g.fillPolygon(p);     // Fills the triangle above.
Redemption answered 24/3, 2009 at 1:42 Comment(1)
how do you set the color to fill the triangle with?Soloma
O
8

You need to specify the vertices of your polygon (in this case, a triangle) and pass to fillPolygon():

  public void paint(Graphics g) 
  {
    int xpoints[] = {25, 145, 25, 145, 25};
    int ypoints[] = {25, 25, 145, 145, 25};
    int npoints = 5;

    g.fillPolygon(xpoints, ypoints, npoints);
  }
Oleo answered 24/3, 2009 at 1:41 Comment(2)
Thanks....but is that mean triangle drawn using Lines cannot be filled with color?Guilt
@Jessy: the intersection of the lines (i.e. the vertices) are the points you require.Oleo
B
0
    public void paintComponent(Graphics g){
         super.paintComponents(g);

      int x[] = {1,2,3};
      int y[] = {4,5,6};
      int npoints = x.length;//or y.length

      g.drawPolygon(x, y, npoints);//draws polygon outline
      g.fillPolygon(x, y, npoints);//paints a polygon

}
Baras answered 16/12, 2018 at 23:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.