Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill color on triangle

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
        }
like image 642
Jessy Avatar asked Mar 24 '09 01:03

Jessy


People also ask

Which method is used to fill Colour in triangle?

g. fillPolygon(p); // Fills the triangle above.

How do you fill a triangle with an applet?

1. Use method drawPolygon and fillPolygon of the Graphics class to draw and fill the shapes – Square, Pentagon, Rectangle and Triangle. 2. Use method drawOval and fillOval of the Graphics class to draw and fill the shapes – Oval and Circle.

How do you paint a triangle in Java?

swing and drawPolygon to Draw a Triangle in Java. We use JFrame to create a top-level container, and then add a panel, which is our DrawATriangle class that extends JPanel , to it. As shown in the code below, we call the drawPolygon method inside the paintComponent to create a triangle on the Graphics object g .


1 Answers

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.
like image 147
John Feminella Avatar answered Oct 09 '22 12:10

John Feminella